【问题标题】:multi splice (or similar) to remove a number of objects in array多拼接(或类似)以删除数组中的多个对象
【发布时间】:2023-01-13 01:15:33
【问题描述】:

所以我目前有 2 个数组:

const getUniqueRowErrors = [1,3]

const data = [
 {identifier: '000'},
 {identifier: '111'},
 {identifier: '222'},
 {identifier: '3333'},
 {identifier: '444'}
]

我的想法是我想删除基于 getUniqueRowErrors 的元素,所以我想从 data 数组中删除第一个和第三个元素,所以最终结果是:

const data = [
 {identifier: '111'},
 {identifier: '3333'},
 {identifier: '444'}
]

我尝试了以下但期望的结果不正确:

const filteredData = getUniqueRowErrors.map((rowToRemove) => data.splice(rowToRemove));

任何想法如何做到以上?

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    只需按索引过滤并检查索引是否在行错误数组中:

    const getUniqueRowErrors = [1,3]
    
    const data = [
     {identifier: '000'},
     {identifier: '111'},
     {identifier: '222'},
     {identifier: '3333'},
     {identifier: '444'}
    ];
    
    console.log(data.filter((_, i) => !getUniqueRowErrors.includes(i + 1)));

    【讨论】:

      【解决方案2】:

      使用Array#filter

      const getUniqueRowErrors = new Set([1,3]);
      const data = [
       {identifier: '000'},
       {identifier: '111'},
       {identifier: '222'},
       {identifier: '3333'},
       {identifier: '444'}
      ]
      let res = data.filter((_, i) => !getUniqueRowErrors.has(i + 1));
      console.log(res);

      【讨论】:

        【解决方案3】:

        您需要向 splice 方法提供一个长度作为第二个参数。在您的情况下,您必须将其设置为 1。此外,由于您不是基于零索引方法删除项目,因此您必须从 rowToRemove 中减去 1。

        data.splice(rowToRemove - 1, 1)
        

        【讨论】:

          猜你喜欢
          • 2021-06-01
          • 2019-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-07
          • 2021-04-28
          • 1970-01-01
          相关资源
          最近更新 更多