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:
xxxxxxxxxx
1
const array = ['a', 'b', 'c'];
2
const value = 'd';
3
4
if (!array.includes(value)) {
5
array.push(value);
6
}
7
8
console.log(array); // [ 'a', 'b', 'c', 'd' ]
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.
xxxxxxxxxx
1
const array = [{ id: 1 }, { id: 2 }];
2
const value = { id: 3 };
3
4
const index = array.findIndex((object) => object.id === value.id);
5
6
if (index === -1) {
7
array.push(value);
8
}
9
10
console.log(JSON.stringify(array, null, 4)); // [ { id: 1 }, { id: 2 }, { id: 3 } ]
Note:
The
findIndex()
method returns-1
if no element passes the provided test.
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
.
xxxxxxxxxx
1
const compare = (array, comparator) => {
2
for (let i = 0; i < array.length; ++i) {
3
if (comparator(array[i])) return true;
4
}
5
return false;
6
};
7
8
const pushIfNotExist = (array, element, comparator) => {
9
if (!compare(array, comparator)) {
10
array.push(element);
11
}
12
};
13
14
15
// Usage example:
16
17
const myArray = [{ id: 1, name: 'Kate' }];
18
19
const object1 = { id: 1, name: 'Kate' }; // already exists
20
const object2 = { id: 2, name: 'Tom' }; // doesn't exist
21
22
pushIfNotExist(myArray, object1, (obj) => obj.id === object1.id && obj.name === object1.name);
23
pushIfNotExist(myArray, object2, (obj) => obj.id === object2.id && obj.name === object2.name);
24
25
console.log(JSON.stringify(myArray, null, 4)); // [ { id: 1, name: 'Kate' }, { id: 2, name: 'Tom' } ]