Skip to content Skip to sidebar Skip to footer

How To Prevent Adding Duplicate Keys To A Javascript Array

I found a lot of related questions with answers talking about for...in loops and using hasOwnProperty but nothing I do works properly. All I want to do is check whether or not a ke

Solution 1:

Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:

var foo = { bar: 0 };

Then use in to check for a key:

if ( !( 'bar'in foo ) ) {
    foo['bar'] = 42;
}

As was rightly pointed out in the comments below, this method is useful only when your keys will be strings, or items that can be represented as strings (such as numbers).

Solution 2:

var a = [1,2,3], b = [4,1,5,2];

b.forEach(function(value){
  if (a.indexOf(value)==-1) a.push(value);
});

console.log(a);
// [1, 2, 3, 4, 5]

For more details read up on Array.indexOf.

If you want to rely on jQuery, instead use jQuery.inArray:

$.each(b,function(value){
  if ($.inArray(value,a)==-1) a.push(value);
});

If all your values are simply and uniquely representable as strings, however, you should use an Object instead of an Array, for a potentially massive speed increase (as described in the answer by @JonathanSampson).

Solution 3:

A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.

vararray = new Set();
array.add(1);
array.add(2);
array.add(3);

console.log(array);
// Prints: Set(3) {1, 2, 3}array.add(2); // does not add any new element

console.log(array);
// Still Prints: Set(3) {1, 2, 3}

Solution 4:

If you're already using spread...

let colors = ['red', 'orange', 'yellow'];
let moreColors = ['orange', 'green'];

let mergedColors = [...colors, ...moreColors];

and want to avoid duplicates...

let mergedColors = [...colors, ...moreColors.filter(c => !colors.includes(c)) ];

Solution 5:

You can try this:

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

Easiest way to find duplicate values in a JavaScript array

Post a Comment for "How To Prevent Adding Duplicate Keys To A Javascript Array"