Travis Michael Heller Travis Michael Heller - 7 months ago 12
Javascript Question

filter out duplicate objects by value name and place into new array

I am trying to filter out duplicates objects in array by object value name and place into new array called finalResult.

Basically i want to only have objects with unique country names in my new array.

example arrays:

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},
];


This is what i want my array to turn out like:

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


Here is my attempt to solve with no luck and only frustration:

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);

Answer

You could filter the data with Array#filter and use an object for already inserted items.

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>');

Comments