首页 > 解决方案 > 使用reduce函数从对象数组中获取唯一值

问题描述

我有一个对象数组

const data = [{
    productId: 7000254,
    quantity: 1
}, {
    productId: 7000255,
    quantity: 1
}, {
    productId: 7000256,
    quantity: 1
}, {
    productId: 7000257,
    quantity: 1
}, {
    productId: 7000254,
    quantity: 1
}];

我需要使用 reduce 函数从中获取唯一值。

我用下面的代码做的

data.map((rp) => {
      if (products.map(({ productId }) => productId).indexOf(rp.productId) === -1) {
        products.push({ productId: parseInt(rp.productId), quantity: 1 })
      }
    })

但正如您所看到的,这是一个漫长的过程,因为我必须多次迭代数组。那么有没有办法使用reduce函数呢?

var unique = data.reduce((a, b ,c,d) => {
  if (a.map(({productId}) => productId).indexOf(b.productId) === -1) {
    return [a,b]
  }
})
console.log(unique)

预期产出

0: {productId: 7000254, quantity: 1}
1: {productId: 7000255, quantity: 1}
2: {productId: 7000256, quantity: 1}
3: {productId: 7000257, quantity: 1}

标签: javascriptarraysuniquereduce

解决方案


您可以使用filterSet有效地实现此结果。

const data = [{
    productId: 7000254,
    quantity: 1,
  },
  {
    productId: 7000255,
    quantity: 1,
  },
  {
    productId: 7000256,
    quantity: 1,
  },
  {
    productId: 7000257,
    quantity: 1,
  },
  {
    productId: 7000254,
    quantity: 1,
  },
];

const set = new Set();
const result = data.filter((o) => {
  if (set.has(o.productId)) return false;
  set.add(o.productId);
  return true;
});

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}


推荐阅读