【问题标题】:JS/ES6/lodash find index of missing elements of two multidimensional arraysJS/ES6/lodash 查找两个多维数组缺失元素的索引
【发布时间】:2020-10-28 01:15:32
【问题描述】:

假设我有 2 个多维对象数组

const products = [
  {
    id: 1
    name: 'lorem'
  },
  {
    id: 3,
    name: 'ipsum'
  }
];

const tmp_products = [
  {
    id: 1
    name: 'lorem'
  },
  {
    id: 14,
    name: 'porros'
  },
  {
    id: 3,
    name: 'ipsum'
  },
  {
    id: 105,
    name: 'dolor'
  },
  {
    id: 32,
    name: 'simet'
  }
];

通过id 属性查找缺失索引的正确方法是什么? 我期待像[1,3,4] 这样的输出,因为products 中不存在这些对象

我发现了一个类似的问题,但适用于普通数组: Javascript find index of missing elements of two arrays

var a = ['a', 'b', 'c'],
  b = ['b'],
  result = [];
_.difference(a, b).forEach(function(t) {result.push(a.indexOf(t))});

console.log(result);

我想使用 ES6 或 lodash 来尽可能短

【问题讨论】:

  • 不,我需要缺少索引而不是缺少 ID,所以我期待 [1,3,4]

标签: javascript arrays indexing ecmascript-6


【解决方案1】:

您可以使用集合来快速完成:

const productIds = new Set(products.map(v => v.id));
const inds = tmp_products
    .map((v, i) => [v, i])
    .filter(([v, i]) => !productIds.has(v.id))
    .map(([v, i]) => i);
inds // [1, 3, 4]

【讨论】:

    【解决方案2】:

    您可以使用Array.prototype.reduce函数获取缺失产品索引列表。

    reduce回调中,您可以使用Array.prototype.some检查产品是否包含在products数组中,并根据该结果决定是否添加product index

    const products = [
      {
        id: 1,
        name: 'lorem'
      },
      {
        id: 3,
        name: 'ipsum'
      }
    ];
    
    const tmp_products = [
      {
        id: 1,
        name: 'lorem'
      },
      {
        id: 14,
        name: 'porros'
      },
      {
        id: 3,
        name: 'ipsum'
      },
      {
        id: 105,
        name: 'dolor'
      },
      {
        id: 32,
        name: 'simet'
      }
    ];
    
    const missingIndex = tmp_products.reduce((acc, curV, curI) => {
      if (!products.some((item) => item.id === curV.id && item.name === curV.name)) {
        acc.push(curI);
      }
      return acc;
    }, []);
    
    console.log(missingIndex);

    【讨论】:

    • 我已将其更改为已接受的答案,因为其他解决方案正在比较整个对象。这样一来,我就可以只关心产品 ID 并据此进行比较。
    【解决方案3】:

    使用 lodash 你可以使用differenceWith:

    _(tmp_products)
      .differenceWith(products, _.isEqual)
      .map(prod => tmp_products.indexOf(prod))
      .value()
    

    这对于性能来说可能不是很好,但这取决于您拥有多少项目。有了你的数组的大小,这应该可以执行。

    【讨论】:

    • 不错的解决方案。我将处理一个不超过 10 个对象的数组,所以这非常适合。除了这是最清晰的,我还可以通过执行 _(tmp_products).differenceWith(products, _.isEqual).map(prod => tmp_products.id).value() 轻松获取缺少的产品 ID
    猜你喜欢
    • 2019-03-07
    • 2011-02-05
    • 2012-11-03
    • 1970-01-01
    • 2022-11-19
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多