In this post, we will learn how to push an element to an array, if the element does not exist with Javascript. While doing projects, we may encounter a situation where we need to add an element to an array. In this post, we will learn 3 ways to push an element to an array if it doesn’t exist.
1. Using IndexOf
const array = ["c", "o", "d", "e"];
const newElement = "i";
// Method 1: Using IndexOf
if (array.indexOf(newElement) === -1) {
array.push(newElement);
}
// Output
// ["c", "o", "d", "e", "i"]
In the above Javascript code, we are using the Array.indexOf() method to determine whether the new element is already present in the array or not.
We will pass the new element to Array.indexOf() method will return the index of the element if it is present in an array otherwise it will return -1. Based on the value returned by the indexOf() method we will add the new item to the array.
2. Using Filter
Let’s see how we use the filter() method to add a unique element to an array.
const array = ["c", "o", "d", "e"];
const newElement = "i";
// Method 2: Using Filter
const filteredArray = array.filter((item) => item === newElement);
if (filteredArray.length === 0) {
array.push(newElement);
}
// Output
// ["c", "o", "d", "e", "i"]
Firstly we will filter the array to check whether the given element is present in the array or not. If the element does not exist, the filter method will return an empty array else we will get an array that contains the given element. If we get an empty array we will push the element using Array.push() method.
const array = [
{ name: "abc", userName: "abc" },
{ name: "xyz", userName: "xyz" },
];
const newElement = { name: "pqr", userName: "pqr" };
// Method 2: Using Filter for array of objects
const filteredArray = array.filter(
(item) => item.userName === newElement.userName
);
if (filteredArray.length === 0) {
array.push(newElement);
}
// Output
// [
// { name: "abc", userName: "abc" },
// { name: "xyz", userName: "xyz" },
// { name: "pqr", userName: "pqr" }
// ]
For an array of objects, we will filter the array with a specific property. If the object with such a property doesn’t exist we will add the object to the array.
3. Using FindIndex
const array = [
{ name: "abc", userName: "abc" },
{ name: "xyz", userName: "xyz" },
];
const newElement = { name: "pqr", userName: "pqr" };
// Method 3: Using FindIdex for an array of objects
if (array.findIndex((item) => item.userName === newElement.userName) === -1) {
array.push(newElement);
}
// Output
// [
// { name: "abc", userName: "abc" },
// { name: "xyz", userName: "xyz" },
// { name: "pqr", userName: "pqr" }
// ]
The findIndex() method will return the index of the element if the element exists in the array otherwise it will return the value as -1. If we get the index value as -1 we will add that element to the array.
Using the above methods we will push an element if it does not exist in an array using Javascript.
Also, Check this