EN
JavaScript - array push() if element doesn't exist in array
0
points
In this article, we would like to show you how to push an element into an array if doesn't exist using JavaScript.
Quick solution for primitive values:
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c'];
const value = 'd';
if (!array.includes(value)) {
array.push(value);
}
console.log(array); // [ 'a', 'b', 'c', 'd' ]
1. Compare objects by property
In this example, we compare objects by a single property - id using findIndex() method. If the object with such id doesn't already exist it will be added using push() method.
// ONLINE-RUNNER:browser;
const array = [{ id: 1 }, { id: 2 }];
const value = { id: 3 };
const index = array.findIndex((object) => object.id === value.id);
if (index === -1) {
array.push(value);
}
console.log(JSON.stringify(array, null, 4)); // [ { id: 1 }, { id: 2 }, { id: 3 } ]
Note:
The
findIndex()method returns-1if no element passes the provided test.
2. Compare multiple object properties
In this example, we create pushIfNotExist() function that uses compare() function to push an object into an myArray if it doesn't already exist. The compare() checks if an object exists in the array by executing the comparator function on every element in array.
// ONLINE-RUNNER:browser;
const compare = (array, comparator) => {
for (let i = 0; i < array.length; ++i) {
if (comparator(array[i])) return true;
}
return false;
};
const pushIfNotExist = (array, element, comparator) => {
if (!compare(array, comparator)) {
array.push(element);
}
};
// Usage example:
const myArray = [{ id: 1, name: 'Kate' }];
const object1 = { id: 1, name: 'Kate' }; // already exists
const object2 = { id: 2, name: 'Tom' }; // doesn't exist
pushIfNotExist(myArray, object1, (obj) => obj.id === object1.id && obj.name === object1.name);
pushIfNotExist(myArray, object2, (obj) => obj.id === object2.id && obj.name === object2.name);
console.log(JSON.stringify(myArray, null, 4)); // [ { id: 1, name: 'Kate' }, { id: 2, name: 'Tom' } ]