Trying To Prevent Duplicate Values To Be Added To An Array.
Having an issue with my project when it comes to adding a duplicate value to an array on a click event. when I push the clicked item's value to the array openedCards.push(card); th
Solution 1:
With vanilla javascript you can do this like the following:
if (array.indexOf(value) === -1) array.push(value);
Where array
is your array of value
's that you don't want duplicates of.
Or, you can use the following es6 syntax:
if (array.includes(value) === false) array.push(value);
Solution 2:
I think you are running into issues with using object reference vs value
While obj and obj2 have same value for underlying properties, they both return different values to $.inArray
arr = [];
obj = {}; obj.A = 2;
arr.push(obj);
obj2 = {}; obj2.A = 2;
console.log($.inArray(obj, arr)); // 0
console.log($.inArray(obj2, arr)); // -1
In this case, I would recommend using some other property of card to check for availability within the array
function containsCard(card, list) {
return list.some(function(elem) {
return elem.A === card.A
})
}
arr = [];
obj = {}; obj.A = 2;
arr.push(obj);
obj2 = {}; obj2.A = 2;
console.log(containsCard(obj, arr)); // true
console.log(containsCard(obj2, arr)); // true
Solution 3:
You can just use $.inArray()
, like:
if(!$.inArray(value, array))array.push(value);
Post a Comment for "Trying To Prevent Duplicate Values To Be Added To An Array."