Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter a table by a specific array of strings and its order using vanilla JS

So i have been tinkering around with apis and i essentially created a table using vanilla javascript and a very lengthy set of sort commands that filter the table by string.

What i would like to achieve is set an object with strings in the order i want to filter by.
Taking the example of "rarity" in a video game. Using this filter, i would like to use this as a sorting function that filters the content in the table by the order that the filter defines.

Common > Uncommon > Rare > Epic > Legendary

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I suppose you would need to give the function the key that you are looking for to compare between each "item" in the data set.

let filter = {
  "COMMON",
  "UNCOMMON",
  "RARE",
  "EPIC",
  "LEGENDARY
}

What would your approach be to this issue?

>Solution :

You can sort the Array like this. Hope this maybe helpful.

dataArray.sort((a, b) => filter.indexOf(a.dataKey) - filter.indexOf(b.dataKey))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading