que1326 que1326 - 1 year ago 83
Javascript Question

How to add non duplicate objects in an array in javascript?

I want to add non-duplicate objects into a new array.

var array = [
id: 1,
label: 'one'
id: 1,
label: 'one'
id: 2,
label: 'two'

var uniqueProducts = array.filter(function(elem, i, array) {
return array.indexOf(elem) === i;

console.log('uniqueProducts', uniqueProducts);
// output: [object, object, object]

live code

Answer Source

Usually, you use an object to keep track of your unique keys. Then, you convert the object to an array of all property values.

It's best to include a unique id-like property that you can use as an identifier. If you don't have one, you need to generate it yourself using JSON.stringify or a custom method. Stringifying your object will have a downside: the order of the keys does not have to be consistent.

You could create an objectsAreEqual method with support for deep comparison, but this will slow your function down immensely.

In two steps:

var array=[{id:1,label:"one"},{id:1,label:"one"},{id:2,label:"two"}];

// Create a string representation of your object
function getHash(obj) {
   return Object.keys(obj)
     .sort() // Keys don't have to be sorted, do it manually here
     .map(function(k) {
       return k + "_" + obj[k]; // Prefix key name so {a: 1} != {b: 1}
     .join("_"); // separate key-value-pairs by a _

function getHashBetterSolution(obj) {
  return obj.id; // Include unique ID in object and use that

// When using `getHashBetterSolution`:
// { '1': { id: '1', label: 'one' }, '2': /*etc.*/ }
var uniquesObj = array.reduce(function(res, cur) {
  res[getHash(cur)] = cur;
  return res;
}, {});

// Convert back to array by looping over all keys                             
var uniquesArr =  Object.keys(uniquesObj).map(function(k) {
  return uniquesObj[k];


// To show the hashes

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download