按值名称过滤掉重复的对象并放入新数组中

时间:2016-05-02 20:41:45

标签: javascript arrays

我试图按对象值名称过滤出数组中的重复对象,并放入名为finalResult的新数组中。

基本上我想在我的新数组中只包含具有唯一国家/地区名称的对象。

示例数组:

var result = [
   {country: 'united states', numofdistributors: 5},
   {country: 'united states', numofdistributors: 5},
   {country: 'brazil', numofdistributors: 2},
   {country: 'Germany', numofdistributors: 1},
   {country: 'india', numofdistributors: 6},
   {country: 'united states', numofdistributors: 5},
   {country: 'Egypt', numofdistributors: 1},
   {country: 'Germany', numofdistributors: 1},
];

这就是我希望我的数组结果如下:

var finalResult = [
   {country: 'united states', numofdistributors: 5},
   {country: 'brazil', numofdistributors: 2},
   {country: 'Germany', numofdistributors: 1},
   {country: 'india', numofdistributors: 6},
   {country: 'Egypt', numofdistributors: 1},
];

这是我试图解决的,没有运气,只有挫折:

var finalResults = [];
result.forEach(function(country){
    if(finalResults.indexOf(country.country) != -1){
        console.log('already added');
    }else {
       //console.log('Does not exist');
       finalResults.push(country);
});
console.log(finalResults);

2 个答案:

答案 0 :(得分:2)

您可以使用Array#filter过滤数据,并使用已插入项目的对象。

var result = [{ country: 'united states', numofdistributors: 5 }, { country: 'united states', numofdistributors: 5 }, { country: 'brazil', numofdistributors: 2 }, { country: 'Germany', numofdistributors: 1 }, { country: 'india', numofdistributors: 6 }, { country: 'united states', numofdistributors: 5 }, { country: 'Egypt', numofdistributors: 1 }, { country: 'Germany', numofdistributors: 1 }, ],
    finalResult = result.filter(function (a) {
        var key = a.country + '|' + a.numofdistributors;
        if (!this[key]) {
            this[key] = true;
            return true;
        }
    }, Object.create(null));

document.write('<pre>' + JSON.stringify(finalResult, 0, 4) + '</pre>');

答案 1 :(得分:1)

你已经完成了。只是一个简单的错误:

var result = [
   {country: 'united states', numofdistributors: 5},
   {country: 'united states', numofdistributors: 5},
   {country: 'brazil', numofdistributors: 2},
   {country: 'Germany', numofdistributors: 1},
   {country: 'india', numofdistributors: 6},
   {country: 'united states', numofdistributors: 5},
   {country: 'Egypt', numofdistributors: 1},
   {country: 'Germany', numofdistributors: 1},
];

var finalResult = [
   {country: 'united states', numofdistributors: 5},
   {country: 'brazil', numofdistributors: 2},
   {country: 'Germany', numofdistributors: 1},
   {country: 'india', numofdistributors: 6},
   {country: 'Egypt', numofdistributors: 1},
];

var finalResults = [];
var countries = [];
result.forEach(function(country){
    if(countries.indexOf(country.country) != -1){
        console.log('already added');
    }else {
       //console.log('Does not exist');
       finalResults.push(country);
       countries.push(country.country);
}
}
);
console.log(finalResults);