【问题标题】:Print duplicate JSON Array in console using Node JS使用 Node JS 在控制台中打印重复的 JSON 数组
【发布时间】:2020-10-27 23:02:21
【问题描述】:

我有一组如下所示的 JSON 数组,我想打印具有相同 URL 的重复 JSON。

var temp = [
  {
     "name":"Allen",
     "site":"www.google.com/allen"
  },
  {
     "name":"Chris",
     "site":"www.google.com/chris"
  },
  {
     "name":"Tom Allen",
     "site":"www.google.com/allen"
  }
]

预期输出:

duplicate = {
 "name":"Allen",
 "site":"www.google.com/allen"
}

【问题讨论】:

  • 添加你尝试过的代码。

标签: javascript node.js npm


【解决方案1】:

在功能方面:

我的函数会将所有不是第一次出现的事件视为“重复”。 您将需要“最后一个”,只需反转集合即可。

// f: a function that receives one element from coll and returns a `key` that identify the element
// coll: any collection that implements .reduce
var duplicatesBy = (f, coll) => {
  var rf = ({dups, seen}, el) => {
    var id = f(el)
    return {
      dups: (seen.includes(id) ? [... dups, el] : dups),
      seen: [... seen, id]
    }
  }
  var { dups } = coll.reduce(rf, {dups: [], seen: []})
  return dups
}

console.log(duplicatesBy(({site})=> site, temp))

//output:
// [ { name: 'Tom Allen', site: 'www.google.com/allen' } ]

【讨论】:

    【解决方案2】:

    首先,duplicate 变量应该是一个数组,因为可能有多个重复对象。并且第一项不应被选为重复项。你可以试试这个-

    var temp = [{"name":"Allen","site":"www.google.com/allen"},{"name":"Chris","site":"www.google.com/chris"},{"name":"Tom Allen","site":"www.google.com/allen"}];
    
    const hashMap = {};
    const duplicate = [];
    
    temp.forEach(item => {
      if (hashMap[item.site] !== undefined) {
        duplicate.push(item);
      } else {
        hashMap[item.site] = item;
      }
    });
    
    console.log(duplicate);

    【讨论】:

    • 如果 (hashMap[item.site] !== undefined) 先生,你能解释一下吗?
    • 这只是一个普通对象,我将site 作为键,item 作为值并检查site 是否已经存在于对象中。如果存在,则意味着它是重复的。
    【解决方案3】:

    let temp = [
    {
     "name":"Allen",
     "site":"www.google.com/allen"
    },
    {
     "name":"Chris",
     "site":"www.google.com/chris"
    },
    {
     "name":"Tom Allen",
     "site":"www.google.com/allen"
    }
    ];
    
    let dups = temp.reduce((r,t,i,o)=>{
       o.some((x,i2)=>x.site===t.site && i!==i2) && !r.some(x=>x.site===t.site) && r.push(t);
       return r;
    },[]);
    
    console.log(dups);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2015-08-23
      • 2020-11-14
      • 2013-11-07
      • 2018-05-16
      • 1970-01-01
      相关资源
      最近更新 更多