js push into array if item exist

JavaScript: Pushing into an array if an item exists

As a web developer, I often come across situations where I need to push an element into an array only if it doesn't already exist. There are several ways to do this in JavaScript, but in this blog post, I will demonstrate how to achieve this using the push() method.

The push() method

The push() method is a built-in function in JavaScript that adds one or more elements to the end of an array and returns the new length of the array. Here's a simple example:

let fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // Output: ['apple', 'banana', 'orange']

In this example, we created an array of fruits and added a new element 'orange' to the end of the array using the push() method.

Pushing a unique element into the array

If we want to push an element into an array only if it doesn't already exist, we can use the indexOf() method to check if the element exists in the array or not. Here's an example:

let fruits = ['apple', 'banana'];
let newFruit = 'orange';
if (fruits.indexOf(newFruit) === -1) {
  fruits.push(newFruit);
}
console.log(fruits); // Output: ['apple', 'banana', 'orange']

In this example, we first checked if the element 'orange' exists in the array using the indexOf() method. If it returns -1, it means the element doesn't exist in the array, so we pushed the 'orange' element into the array using the push() method.

Using includes() method instead of indexOf()

The includes() method is another way to check if an element exists in an array or not. Here's how we can modify the previous example to use the includes() method:

let fruits = ['apple', 'banana'];
let newFruit = 'orange';
if (!fruits.includes(newFruit)) {
  fruits.push(newFruit);
}
console.log(fruits); // Output: ['apple', 'banana', 'orange']

This code works similarly to the previous example. We first checked if the element 'orange' exists in the array using the includes() method. If it returns false, it means the element doesn't exist in the array, so we pushed the 'orange' element into the array using the push() method.

Conclusion

In this blog post, we learned how to push an element into an array only if it doesn't already exist using the push() method and the indexOf() or includes() methods. Using these methods, we can easily add unique elements to an array without duplicates.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe