Leon Gaban
Leon Gaban

Reputation: 39018

How to prevent pushing value into Array twice? (jQuery)

I have a function which grabs a unique number from a data attribute in HTML. In my case it's called data-key which will have a unique number.

Now when a button is clicked next to HTML element that has a data-key, that key number is pushed into an Array.

I don't want the same number put into the array more than once.

Is there a simple way to accomplish this? The way I'm imagining doing it is to check to see if that element is already in the Array first before pushing, but I feel like there is a simpler way?

My Codepen: http://codepen.io/leongaban/pen/CEfxi

Click on the enter image description here button to add an input value into the array.

enter image description here < 6-1 gets added twice

jQuery

var deletedArray = [];

$('.remove_info').unbind('click').bind("click", function(event) {
    //console.log('clicked remove x');
    var value = $(this).prev().attr('value');
    var key = $(this).prev().data('key');

    deletedArray.push(key);
    console.log('this value = '+value+' deletedArray = '+deletedArray);
});

Upvotes: 0

Views: 5448

Answers (2)

Jay Harris
Jay Harris

Reputation: 4271

Should've been a comment but put a control statement before the push function call

  if (deletedArray.indexOf(key) < 0) deletedArray.push(key);

For browser compatibility jQuery's inArray

  if ($.inArray(key, deletedArray) < 0) deletedArray.push(key);

Note: indexOf is not compatible with IE 8 and earlier

Upvotes: 8

Konstantin K
Konstantin K

Reputation: 1317

If all elements in your array must be unique, then I would really recommend using Underscore's array union:

arr = ["1", 2, "apple"];

console.log(_.union(arr, 3)); //["1", 2, "apple", 3]
console.log(_.union(arr, 2)); //["1", 2, "apple"]

Upvotes: 0

Related Questions