我有一个包含对象数组的对象。

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

当前回答

str =[
{"item_id":1},
{"item_id":2},
{"item_id":2}
]

obj =[]
for (x in str){
    if(check(str[x].item_id)){
        obj.push(str[x])
    }   
}
function check(id){
    flag=0
    for (y in obj){
        if(obj[y].item_id === id){
            flag =1
        }
    }
    if(flag ==0) return true
    else return false

}
console.log(obj)

str是一个对象数组。存在具有相同值的对象(这里是一个小示例,有两个对象的item_id与2相同)。check(id)是一个函数,用于检查是否存在任何具有相同itemid的对象。如果存在,则返回false,否则返回true。根据该结果,将对象推入新的数组obj上述代码的输出为[{“item_id”:1},{“item_id”:2}]

其他回答

这里有一个使用JavaScript新过滤功能的解决方案,非常简单。假设你有一个这样的数组。

var duplicatesArray = ['AKASH','AKASH','NAVIN','HARISH','NAVIN','HARISH','AKASH','MANJULIKA','AKASH','TAPASWENI','MANJULIKA','HARISH','TAPASWENI','AKASH','MANISH','HARISH','TAPASWENI','MANJULIKA','MANISH'];

filter函数将允许您为数组中的每个元素使用一次回调函数来创建一个新数组。所以你可以这样设置唯一的数组。

var uniqueArray = duplicatesArray.filter(function(elem, pos) {return duplicatesArray.indexOf(elem) == pos;});

在这种情况下,您的唯一数组将遍历重复数组中的所有值。elem变量表示数组中元素的值(mike、james、james和alex),位置是它在数组中的0索引位置(0,1,2,3…),duplicatesArray.indexOf(elem)值只是该元素在原始数组中第一次出现的索引。因此,因为元素'james'是重复的,所以当我们循环遍历duplicatesArray中的所有元素并将它们推送到uniqueArray时,第一次命中james时,我们的“pos”值为1,indexOf(elem)也为1,因此james被推送到unique Array。第二次命中James时,我们的“pos”值为2,indexOf(elem)仍然为1(因为它只找到数组元素的第一个实例),因此不会推送重复项。因此,uniqueArray只包含唯一值。

这是上述功能的演示。单击此处查看上述功能示例

另一种方法是使用reduce函数,并使用一个新数组作为累加器。如果累加器数组中已经有一个同名的对象,那么不要将其添加到那里。

let list = things.thing;
list = list.reduce((accumulator, thing) => {
    if (!accumulator.filter((duplicate) => thing.name === duplicate.name)[0]) {
        accumulator.push(thing);
    }
    return accumulator;
}, []);
thing.things = list;

我添加了这个答案,因为我找不到与InternetExplorer11兼容的好的、可读的es6解决方案(我使用babel来处理箭头函数)。问题是IE11没有没有polyfill的Map.values()或Set.values)。出于同样的原因,我使用filter()[0]来获取第一个元素,而不是find()。

const uniqueElements = (arr, fn) => arr.reduce((acc, v) => {
    if (!acc.some(x => fn(v, x))) { acc.push(v); }
    return acc;
}, []);

const stuff = [
    {place:"here",name:"stuff"},
    {place:"there",name:"morestuff"},
    {place:"there",name:"morestuff"},
];

const unique = uniqueElements(stuff, (a,b) => a.place === b.place && a.name === b.name );
//console.log( unique );

[{
    "place": "here",
    "name": "stuff"
  },
  {
    "place": "there",
    "name": "morestuff"
}]

removeDucplicates()接受一个对象数组,并返回一个没有任何重复对象的新数组(基于id属性)。

const allTests = [
  {name: 'Test1', id: '1'}, 
  {name: 'Test3', id: '3'},
  {name: 'Test2', id: '2'},
  {name: 'Test2', id: '2'},
  {name: 'Test3', id: '3'}
];

function removeDuplicates(array) {
  let uniq = {};
  return array.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true))
}

removeDuplicates(allTests);

预期结果:

[
  {name: 'Test1', id: '1'}, 
  {name: 'Test3', id: '3'},
  {name: 'Test2', id: '2'}
];

首先,我们将变量uniq的值设置为空对象。

接下来,我们过滤对象数组。Filter创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

return array.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true));

上面,我们使用了&&的短路功能。如果&&的左侧求值为true,则返回&&右侧的值。如果左侧为false,则返回&&左侧的内容。

对于每个对象(obj),我们检查uniq中名为obj.id值的属性(在这种情况下,在第一次迭代时,它将检查属性“1”。)我们希望它返回的结果(true或false)相反,这就是为什么我们使用!在里面uniq[obj.id]。如果uniq已经具有id属性,则返回true,其计算结果为false(!),告诉过滤函数不要添加该obj。但是,如果未找到obj.id属性,它返回false,然后计算结果为true(!)并返回&&或(uniq[obj.id]=true)右侧的所有内容。这是一个truthy值,告诉filter方法将该obj添加到返回的数组中,并且还将属性{1:true}添加到uniq中。这确保不会再添加具有相同id的任何其他obj实例。

使用ES6“reduce”和“find”数组助手方法的简单解决方案

工作效率高,非常好!

"use strict";

var things = new Object();
things.thing = new Array();
things.thing.push({
    place: "here",
    name: "stuff"
});
things.thing.push({
    place: "there",
    name: "morestuff"
});
things.thing.push({
    place: "there",
    name: "morestuff"
});

// the logic is here

function removeDup(something) {
    return something.thing.reduce(function (prev, ele) {
        var found = prev.find(function (fele) {
            return ele.place === fele.place && ele.name === fele.name;
        });
        if (!found) {
            prev.push(ele);
        }
        return prev;
    }, []);
}
console.log(removeDup(things));