简体   繁体   中英

array filtering javascript

I have these variabiles in js:

 var arr = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'],['name3', 8, 'filter3'], ['name4', 1, 'filter2']]; var filter = 'filter1' //(this variable may have values: filter1, filter2, filter3)*.

How can I filter the array arr according to the filter variable values?

My example must return:

 var arr = [['name2', 5], ['name4', 1]];

By using filter method you can easily test what you want and only return the match elements

 var arr = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'],['name3', 8, 'filter3'], ['name4', 1, 'filter2']]; var filter = 'filter2'; var result = arr.filter(function(res){ return res[2] == filter; }).map(function(filtered){ return filtered.slice(0,2); }); console.log(result);

Beside the filtering, you need to get only the first two elements of the inner arrays.

Array#filter returns the same elements in the array. For getting the wanted items without the filter item, you need to return either the first two objects, or filter the items with the given filter as well (proposal 2).

 var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']], filter = 'filter2', result = array.filter(a => a[2] === filter).map(a => a.slice(0, 2)); console.log(result);

 var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']], filter = 'filter2', result = array .filter(a => a.some(v => v === filter)) .map(a => a.filter(v => v !== filter)); console.log(result);

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