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

时间:2018-02-27 13:28:02

标签: javascript arrays javascript-objects

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

目前我有

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',
}]

3 个答案:

答案 0 :(得分:0)

您可以使用filter。它需要一个谓词,如果谓词返回true,它将返回一个元素。我使用excludes作为谓词,如果当前false位于index内,它将返回indicesToRemove

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))
)




答案 1 :(得分:-1)

您可以将过滤器与索引变量一起使用,这样您就可以根据索引保留所需内容:

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

或指定您不想要的索引:

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

答案 2 :(得分:-2)

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);