[英]How to delete multiple objects from an array?
How to delete multiple objects from an array?如何从数组中删除多个对象?
Currently I have目前我有
let arry1 = [
{
id:0,
name:'My App',
another:'thing',
},
{
id:1,
name:'My New App',
another:'things'
},
{
id:2,
name:'My New App',
another:'things'
}
];
Then I have an indexes array like this然后我有一个这样的索引数组
let arry2 = [1, 2]; // Indexes to delete
finally the result has to be:最后结果必须是:
let arry1 = [{
id:0,
name:'My App',
another:'thing',
}]
You can use filter
.您可以使用filter
。 It expects an predicate and will return an elemtent if the predicate returns true
.它需要一个谓词,如果谓词返回true
,它将返回一个元素。 I used excludes
as predicate and it will return false
if the current index
is inside the indicesToRemove
.我使用excludes
作为谓词,如果当前index
在indicesToRemove
内,它将返回false
。
objects.filter((object, index) => excludesIndicesToRemove(index))
const objects = [{ id: 0, name: 'My App', another: 'thing', }, { id: 1, name: 'My New App', another: 'things' }, { id: 2, name: 'My New App', another: 'things' } ] const indicesToRemove = [1, 2] const not = bool => !bool const includes = xs => x => xs.includes(x) const excludes = xs => x => not(includes(xs)(x)) const excludesIndicesToRemove = excludes(indicesToRemove) console.log( objects.filter((object, index) => excludesIndicesToRemove(index)) )
You can use filter with an index variable, so you can keep what you want depending on its index:您可以将过滤器与索引变量一起使用,因此您可以根据其索引保留所需的内容:
let arr2 = arr1.filter( (e,i) => i !== 2 && i !== 1);
Or specifying the indexes you don't want:或者指定您不想要的索引:
let arr2 = arr1.filter( (e,i) => [2,1].indexOf(i) === -1);
filter
is immutable in that it does not modify the original array. filter
是不可变的,因为它不会修改原始数组。 If you want to modify arry1
, use splice
.如果要修改arry1
,请使用splice
。
arry2.sort((a, b) => b - a).forEach(e => arry1.splice(e, 1))
let arry1 = [ { id:0, name:'My App', another:'thing', }, { id:1, name:'My New App', another:'things' }, { id:2, name:'My New App', another:'things' } ]; let arry2 = [1, 2]; // Indexes to delete arry2.sort((a, b) => b - a).forEach(e => arry1.splice(e, 1)); console.log(arry1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.