如何使用ES6从对象数组中删除重复项?

时间:2018-03-07 19:00:09

标签: javascript react-native ecmascript-6

我想知道合并2个对象数组itemsAitemsB的最佳方法是什么。合并后的数据应位于mergedList中。

标准:

  1. source='STAPLE'项不应在合并数组中重复。
  2. 包含任何其他来源的项目可能会重复。例如,name: 'Ball'source: 'USER'可能会存在两次。
  3. itemsA有6件商品,itemsB有7件商品,mergedList应该有11件商品

    let itemsA = [
    {name: 'Milk', source: 'STAPLE'},
    {name: 'Bread', source: 'AD'},
    {name: 'Egg', source: 'STAPLE'},
    {name: 'Ball', source: 'USER'},
    {name: 'Pasta', source: 'STAPLE'},
    {name: 'Coke', source: 'AD'}];
    let itemsB = [
    {name: 'Milk', source: 'USER'},
    {name: 'Bread', source: 'AD'},
    {name: 'Egg', source: 'STAPLE'},
    {name: 'Ball', source: 'USER'},
    {name: 'Mango', source: 'USER'},
    {name: 'Pasta', source: 'STAPLE'},
    {name: 'Coke', source: 'USER'}]
    

    mergedList应该等于

    let mergedList = [
    {name: 'Milk', source: 'STAPLE'},
    {name: 'Bread', source: 'AD'},
    {name: 'Egg', source: 'STAPLE'},
    {name: 'Ball', source: 'USER'},
    {name: 'Pasta', source: 'STAPLE'},
    {name: 'Coke', source: 'AD'}] 
    {name: 'Milk', source: 'USER'},
    {name: 'Bread', source: 'AD'},
    {name: 'Ball', source: 'USER'},
    {name: 'Mango', source: 'USER'},
    {name: 'Coke', source: 'USER'}]   ];
    

1 个答案:

答案 0 :(得分:1)

function merge(itemsA, itemsB) {
  let merged = [];
  itemsA.concat(itemsB).reduce((stapleSet, obj) => (obj.source != "STAPLE") ?
  (merged.push(obj), stapleSet) : 
  (stapleSet.has(obj.name) || merged.push(obj), 
  stapleSet.add(obj.name), stapleSet), new Set());

  return merged;
}
  • 获得两个阵列。
  • 创建合并数组以将对象推送到。
  • 将两个项目数组连接在一起。
  • 减少连接数组 - 如果对象源是主要的而不在stapleSet中,则将对象的名称添加到stapleSet - 设置对象只允许每个条目中的一个 - 然后将对象推送到merged数组。否则将对象推送到merged数组。

  • 从函数返回合并的数组。



let itemsA = [
{name: 'Milk', source: 'STAPLE'},
{name: 'Bread', source: 'AD'},
{name: 'Egg', source: 'STAPLE'},
{name: 'Ball', source: 'USER'},
{name: 'Pasta', source: 'STAPLE'},
{name: 'Coke', source: 'AD'}];
let itemsB = [
{name: 'Milk', source: 'USER'},
{name: 'Bread', source: 'AD'},
{name: 'Egg', source: 'STAPLE'},
{name: 'Ball', source: 'USER'},
{name: 'Mango', source: 'USER'},
{name: 'Pasta', source: 'STAPLE'},
{name: 'Coke', source: 'USER'}];

    function merge(itemsA, itemsB) {
      let merged = [];
      itemsA.concat(itemsB).reduce((stapleSet, obj) => (obj.source != "STAPLE") ?
      (merged.push(obj), stapleSet) : 
      (stapleSet.has(obj.name) || merged.push(obj), 
      stapleSet.add(obj.name), stapleSet), new Set());

      return merged;
    }
    console.log( merge(itemsA, itemsB) );




修改:OP的其他格式

function merge(itemsA, itemsB) {
  let merged = [];
  itemsA.concat(itemsB).reduce((stapleSet, obj) => {
    if (obj.source != "STAPLE") {
      merged.push(obj);
      return stapleSet;
    } else {
      if (stapleSet.has(obj.name)) {
        return stapleSet;
      } else {
        merged.push(obj);
        stapleSet.add(obj.name);
        return stapleSet;
      }
    }
  }, new Set());
  return merged;
}