简体   繁体   中英

How to filter an array with data with multiple criteria

I have an array that contains information. The data has a tag attribute on which I want to filter.

If the array contains data, the filter should be triggered on all data in the array. If there is no data in the array, then I get all the data from the array with data.

I need control array length for this I need to use includes for max data after filter 30

 //exist array with data const arr = [ { "value": "food", "tag": "food" }, { "value": "drink1", "tag": "drink" }, { "value": "drink2", "tag": "drink" }, { "value": "empty tag data", "tag": null } ]; //example data from request with tags for filtering const data1 = ["food", "drink"]; const data2 = []; function example(arrayForSearch, needToFind) { //not work o.tag.includes(needToFind, 30) return arrayForSearch.reduce((a, o) => (o.tag.includes(needToFind) && a.push(o.value), a), []); } // result (0, 1, 2) indexes from array console.log(example(arr, data1)); // result all data from array console.log(example(arr, data2));

You can use Array.filter() to return the items you wish. If needToFind is empty it will return all items in the array:

 const arr = [ { "value": "food", "tag": "food" }, { "value": "drink1", "tag": "drink" }, { "value": "drink2", "tag": "drink" }, { "value": "empty tag data", "tag": null } ]; const data1 = ["food", "drink"]; const data2 = []; function example(arrayForSearch, needToFind) { // Return any item with a tag in the needToFind array _or_ if the needToFind array is empty. return arrayForSearch.filter(el => needToFind.length === 0 || needToFind.includes(el.tag)); } console.log('data1 result:', example(arr, data1)); console.log('data2 result:', example(arr, data2));

You can use Array.filter() instead of Array.reduce() and switch the operand and the argument for Array.includes() function as followings:

 const arr = [ { "value": "food", "tag": "food" }, { "value": "drink1", "tag": "drink" }, { "value": "drink2", "tag": "drink" }, { "value": "empty tag data", "tag": null } ]; const data1 = ["food", "drink"]; const data2 = []; function example(arrayForSearch, needToFind) { return Array.isArray(needToFind) && needToFind.length > 0? arrayForSearch.filter(item => needToFind.includes(item.tag)): arrayForSearch } console.log(example(arr, data1)); console.log(example(arr, data2));

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