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:

JavaScript

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

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement