简体   繁体   中英

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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM