简体   繁体   中英

Javascript, subset array with more than one selecting element

How do I use an array to subset another array, arrayTotal is array is the array I need to subset

arrayTotal = ['a','a','a','b','b','c','c','c','d','d','d','d','d']

arraySelectors is the array of search terms,

arraySelectors = ['a','d']

The output i'd like to achieve is either,

['a','a','a','d','d','d','d','d']

or

[0,1,2,8,9,10,11,12]

I know this can be done with two loops, but i'd like a more elegant option.

While you can use something like the array includes method, I would recommend using something like Set as it scales very well (hash table efficiency, O(1) lookup for each item). See below for an example.

 const arrayTotal =['a','a','a','b','b','c','c','c','d','d','d','d','d']; arraySelectors = new Set(['a','d']); const filtered = arrayTotal.filter(el => arraySelectors.has(el)); console.log(filtered);

You can achieve this with a combination of filter and includes :

const filteredArray = arrayTotal.filter(value => arraySelectors.includes(value))

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