【问题标题】:How to delete multiple objects from an array?如何从数组中删除多个对象?
【发布时间】:2018-08-07 04:01:20
【问题描述】:

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

目前我有

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

【问题讨论】:

标签: javascript arrays javascript-objects


【解决方案1】:

您可以使用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))
)

【讨论】:

  • 您提到了可读性,但您在同一个方法名称中使用了“not”、“include”和“remove”。例如,使用“排除”比使用“不包括”更好。也许像 excludeIndices([1,2]) 这样的东西更具可读性。
  • 很好,但是在 FP 中 not 也可以是一个函数,not = f => a => !f(a) 然后您可以将 excludes 简单地定义为 xs => not(includes(xs))
【解决方案2】:

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

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

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2023-01-16
      • 2021-01-28
      • 2017-06-15
      • 1970-01-01
      相关资源
      最近更新 更多