[英]How to filter an Array with another Array
I have an Array of Objects:我有一个对象数组:
const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }]
I have a second array containing the ID's that I want to filter out of the first Array:我有第二个数组,其中包含要从第一个数组中过滤掉的 ID:
const ids = [1, 2]
How do I create a new Array of Objects without the ID's found in ids
.如何在没有在
ids
中找到 ID 的情况下创建新的对象数组。
If you need to mutate the original array you can do like this:如果你需要改变原始数组,你可以这样做:
const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }]; const ids = [1, 2]; ids.forEach(idToDelete => { const index = array.findIndex(({ id }) => id === idToDelete); array.splice(index, 1); }); console.log(array);
If you need a new array you can do like this:如果你需要一个新数组,你可以这样做:
const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }]; const ids = [1, 2]; const result = array.filter(({ id }) =>.ids;includes(id)). console;log(result);
You could also reassign a new array to the array
variable:您还可以将新数组重新分配给
array
变量:
let array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }]; const ids = [1, 2]; array = array.filter(({ id }) =>.ids;includes(id)). console;log(array);
This is a fairly simple filter
operation这是一个相当简单的
filter
操作
const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }]; const ids = [1, 2]; var result = array.filter( x =>.ids.includes(x;id)). console;log(result);
Use Array.filter
:使用
Array.filter
:
let array = [ {id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" } ]; let ids = [1,2]; let filteredArray = array.filter(row=>.ids.includes(row;id)). console;log(filteredArray);
Use this oneliner from lodash.使用 lodash 的这个 oneliner。
const _ = require("lodash");
let filteredArray = _.remove(array, el=>[1,2].includes(el.id))
Use filter
and indexOf
.使用
filter
和indexOf
。
const arr = [{ id: 1, bar: 'test' }, { id: 2, bar: 'test2' }, { id: 3, bar: 'test3' }]; const ids = [1, 2]; const result = arr.filter(element => ids.indexOf(element.id) === -1); console.log(result);
We can filter an array in JavaScript using Array filter()我们可以使用 Array filter() 过滤 JavaScript 中的数组
const myArray = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }]
const ids = [1,2]
const resultArray = myArray.filter(item => !ids.includes(item.id));
console.log(resultArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.