Skip to content
Advertisement

Vue/Javascript – Sort array of objects based on its existence in another array

I have two arrays, array1 has all objects and array2 has filtered objects based on a search string.

Currently I am rendering array2 (which will contain all objects from array1 when the search string is empty, but will return only filtered objects if search string isn’t empty) to the user but I would like to show all objects and style the filtered ones (those which match the search) differently and keep those matching the search query in the top of the array/list and if I even in addition to that could also sort those matched objects alphabetically I would love to.

Here is how I am filtering based on the search query:

JavaScript

And in my template I am rendering them this way (to show all objects but style them differently):

JavaScript

How can I implement the sorting as mentioned above?

Advertisement

Answer

Use the spread operator to append the original array to the result of the filtered array like this

JavaScript

This adds the matches to the beginning of the array, next we remove duplicates from the array, and we can do that just by wrapping the new Set() around it, just like this

JavaScript

You can convert it to a plain array just like this.

JavaScript

See Example code below:

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