Skip to content Skip to sidebar Skip to footer

Duplicates In Object Array

EDITED!! I have an object array: Array 0:[{id:'a1' , code:'123' , name:'a'}, {id: 'a2', code: '222' , name: 'a'}, {id: 'b1', code: '433', name: 'b'}] Array 1:[{i

Solution 1:

function filterByName(array) {
    var counts = {};

    array.forEach(function(obj) { 
        counts[obj.name] ? ++counts[obj.name] : (counts[obj.name] = 1);
    });

    return array.filter(function(obj) { 
        return counts[obj.name] === 1;
    });
}

var filteredArray1 = filterByName(array1);
var filteredArray2 = filterByName(array2);

Explanation of function

  1. Create temporary counts object for keeping counts of object with the same name.
  2. Fill this object with data by using standard forEach method of array.
  3. Filter array by using standard filter method

UPD You need this if I understand your question correctly at last:

var filteredArray = arrayOfArrays.map(function(arrayOfObjects) {
  return filterByName(arrayOfObjects)[0];
});

Post a Comment for "Duplicates In Object Array"