The array allows you to store multiple elements in a single object.
You can push elements to an array if it does not exist using the includes() method and the array.push() method.
This tutorial teaches you different methods to use array.push()
to insert an element if the element does not exist in the array.
Table of Contents
Array Push If does Not Exists Using Includes Method
The includes() method checks if the element exists in the JavaScript array.
- If the element already exists, it returns
True
- If the element doesn’t exist, it returns
False
You can check if the element exists using the if
statement and includes()
.
- If the condition passes, then push the element to the array
- Else, do nothing
The includes()
method doesn’t accept any callback function. It accepts only a search element. Hence you cannot check any specific property of a JavaScript object.
Use this method when you are working with primitive types such as int
or chars
.
Code
const array1 = ['owl', 'parrot'];
const newvalue = 'dove';
if (!array1.includes(newvalue)) {
array1.push(newvalue);
}
console.log(array1);
Output
The element dove doesn’t exist. Hence it is pushed to the array.
["owl", "parrot", "dove"]
Array Push If does Not Exists Using FindIndex
The findindex() method returns the first index of an element in the array.
If the element doesn’t exist, it returns -1
.
To push an element if it doesn’t exist,
- Find the element’s index, and if it returns
-1
, push the new element to the array.
The findIndex()
method accepts the callback function as input. Hence you can define a function and check any specific property of a JavaScript object.
Use this method when you work with the JavaScript Objects array instead of primitive types.
Code
The following code checks if an object with a specified already exists in the array and inserts it if it doesn’t exist.
const array2 = [{
id: 1
}, {
id: 2
}];
const newobject = {
id: 3
};
const index = array2.findIndex(object => object.id === newobject.id);
if (index === -1) {
array2.push(newobject);
}
console.log(array2);
Array Push If does Not Exists Using indexof
The indexOf() returns the index of the first occurrence of the element in the array.
If the element doesn’t exist, it returns -1
.
To push an element if it doesn’t exist,
- Find the element’s index, and if it returns
-1
, push the new element to the array.
Use this method when you work with primitives and want to insert an element if it doesn’t exist, and if it exists, you want to perform some other action based on the index.
Code
const array1 = ['owl', 'parrot'];
const newvalue = 'dove';
const elementIndex = array1.indexOf(newvalue)
if (!elementIndex != -1) {
array1.push(newvalue);
} else {
//do something else with the element index
}
console.log(array1);
Output
["owl", "parrot", "dove"]