繁体   English   中英

如何从数组中删除多个对象?

[英]How to delete multiple objects from an array?

如何从数组中删除多个对象?

目前我有

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

最后结果必须是:

let arry1 = [{
    id:0,
    name:'My App',
    another:'thing',
}]

您可以使用filter 它需要一个谓词,如果谓词返回true ,它将返回一个元素。 我使用excludes作为谓词,如果当前indexindicesToRemove内,它将返回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)) )

您可以将过滤器与索引变量一起使用,因此您可以根据其索引保留所需的内容:

let arr2 = arr1.filter( (e,i) => i !== 2 && i !== 1);

或者指定您不想要的索引:

let arr2 = arr1.filter( (e,i) => [2,1].indexOf(i) === -1);

filter是不可变的,因为它不会修改原始数组。 如果要修改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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM