skip to Main Content

I have an array of objects

let array = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]

I am trying to implement with below logic

 array.filter((item) => {
    return item.name.toLowerCase().includes(searchText);
  });

I am trying to search based on "po", when i search with po i am able to get all the records in the same order.

But i need to get the results in the below order to match the first characters

Current output:

[{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]

Expected output:

[{name: "poland"}, {name: "portugal"}, {name: "singpore"}, {name: "French Polynesia"}]

2

Answers


  1. You can use indexOf then sort the values using the indexes!

    let array = [{
      name: "singpore"
    }, {
      name: "French Polynesia"
    }, {
      name: "poland"
    }, {
      name: "portugal"
    }]
    const searchText = 'po';
    console.log(array.filter((item) => {
        return item.name.toLowerCase().includes(searchText);
    }).sort((a, b) => {
      const indexA= a.name.toLowerCase().indexOf(searchText);
      const indexB= b.name.toLowerCase().indexOf(searchText);
      return indexA - indexB;
    }));
    Login or Signup to reply.
  2. You can achieve this by using the sort() after filtering

    let array = [
      { name: "singpore" },
      { name: "French Polynesia" },
      { name: "poland" },
      { name: "portugal" }
    ];
    
    let searchText = "po";
    
    let filteredArray = array
      .filter((item) => item.name.toLowerCase().includes(searchText))
      //compare the index of the search text in each name
      .sort((a, b) => a.name.toLowerCase().indexOf(searchText) - b.name.toLowerCase().indexOf(searchText));
    
    console.log(filteredArray);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search