Array.filter()删除重复的对象

时间:2018-11-09 12:55:14

标签: javascript arrays

我想融合Array.filter()函数以删除重复的对象 我能够在字符串或整数数组的情况下实现。但是我无法通过对象数组达到与names

的第二种情况相同的效果
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let x = names => names.filter((v, i, arr) => arr.indexOf(v) === i);
console.log(x(names)); //[ 'John', 'Paul', 'George', 'Ringo' ]


const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" } ];
// returns the same original array

能请你帮忙吗?

7 个答案:

答案 0 :(得分:3)

使用Array#reduce()Map累加器,然后将Map的values()散布到数组中

const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" } ];

const unique = [... names.reduce((a,c)=>(a.set(c.name,c)),new Map).values()]

console.log(unique)

答案 1 :(得分:2)

使用Array.reduceObject.values

遍历array,并从数组中创建objectkey的{​​{1}}和namevalue的{​​{1}}。如果object具有相同的名称,则objects将在结果对象中被覆盖。最后使用value收集所有唯一的Object.values

objects

要进行调整-Plunker

答案 2 :(得分:1)

const names = [
  { name: "John" },
  { name: "Paul" },
  { name: "George" },
  { name: "Ringo" },
  { name: "John" }
];
/*  unique          => Filter: Remove all duplicate items from an array. Works with plain objects as well, since we stringify each array item.
*   @type           public Function
*   @name           unique
*   @return         Function( item )
*   @notes          
*/
const unique = () => {
    const seen = {};
    return item => {
        const json = JSON.stringify( item );
        return seen.hasOwnProperty( json )
            ? false
            : ( seen[ json ] = true );
    };
};
const result = names.filter( unique() );
console.log( result );

答案 3 :(得分:0)

您可以为此使用lodash的_uniqBy

const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" } ];

const result = _uniqBy(names, 'name');

答案 4 :(得分:0)

这也可以借助Sets来完成

var names = [{ name: "John" },{ name: "Paul" },{ name: "George" },{ name: "Ringo" },{ name: "John" } ];

var result = Array.from(
                         names.reduce((s, d) => s.add(d.name), new Set)
                         , d => ({ name: d })
                       )

console.log(result)

答案 5 :(得分:0)

Keith曾建议将findIndexfilter一起使用,而不是indexOf。对象文字始终是唯一的引用,因此我们无法对其进行比较。但是,我们可以比较对象之间的name键。我们可以使用上述功能来做到这一点。

const names = [
  { name: "John" },
  { name: "Paul" },
  { name: "George" },
  { name: "Ringo" },
  { name: "John" }
];
console.log(names.filter(({name1}, i, a) => {
  return i == a.findIndex(({name2}) => {
    return name1 == name2;
  });
});

答案 6 :(得分:-1)

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups(names) {
let unique = {};
names.forEach(function(i) {
if(!unique[i]) {
  unique[i] = true;
}
});
return Object.keys(unique);
}
removeDups(names); //'John', 'Paul', 'George', 'Ringo'