Skip to content
Advertisement

prioritize pushing element to array

I have an array with objects as elements. What I did was check if the titles value contains a certain string and it it does push that a new array and log the new array and the process works.

What I want is when pushing to the new array I want to prioritize the string found first to be pushed first.

To explain it better say my array is this:

myArr = [{"title": "test hello"}, {"title": "hello test"}, {"title": "test test"}]

If my search string is hello I want my new array to be this:

[{"title": "hello test"}, {"title": "test hello"}]

The search string found first will be put first. How can I achieve this? Thanks in advance.

const myArr = [{
  "title": "test hello"
}, {
  "title": "hello test"
}, {
  "title": "test test"
}]

const searchValue = 'Hello'

let foundArr = []

for (var i = 0; i < myArr.length; i++) {
  if (myArr[i].title.toLowerCase().includes(searchValue.toLowerCase())) {
    foundArr.push(myArr[i])
  }
}

//expected output [{"title": "hello test"}, {"title": "test hello"}]
console.log(foundArr)

Advertisement

Answer

To achieve what you require you could sort() the array by the index of the matched string within the value.

Also, you can simplify the logic by using filter() to find matches instead of an explicit for loop:

const myArr = [
  { title: "test hello" }, 
  { title: "hello test" }, 
  { title: "test test" }, 
  { title: "foo hello test" }
]

const searchValue = 'Hello'.toLowerCase();
let foundArr = myArr
  .filter(o => o.title.toLowerCase().includes(searchValue))
  .sort((a, b) => a.title.toLowerCase().indexOf(searchValue) > b.title.toLowerCase().indexOf(searchValue) ? 1 : -1);

console.log(foundArr)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement