Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 key exists in an array and if not, add it.

I start with an empty array then add keys as the page is scrubbed with jQuery.

Initially, I hoped that something simple like the following would work: (using generic names)

if (!array[key])    array[key] = value; 

No go. Followed it up with:

for (var in array) {    if (!array.hasOwnProperty(var))       array[key] = value; } 

Also tried:

if (array.hasOwnProperty(key) == false)    array[key] = value; 

None of this has worked. Either nothing is pushed to the array or what I try is no better than simply declaring array[key] = value Why is something so simple so difficult to do. Any ideas to make this work?

like image 538
iamsar Avatar asked May 25 '12 15:05

iamsar


People also ask

How can you eliminate duplicate values from a JavaScript array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

Does JavaScript array allow duplicates?

To check if an array contains duplicates: Pass the array to the Set constructor and access the size property on the Set . Compare the size of the Set to the array's length. If the Set contains as many values as the array, then the array doesn't contain duplicates.

Can array have two same keys?

Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.


2 Answers

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

like image 86
Sampson Avatar answered Sep 21 '22 14:09

Sampson


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

like image 31
Phrogz Avatar answered Sep 21 '22 14:09

Phrogz