How to push to an array only if the value doesn’t exist with JavaScript?

Estimated read time 1 min read

You can use the Array.prototype.includes() method in JavaScript to check if an array includes a specific value, and only push the value to the array if it doesn’t exist yet. Here’s an example:

let arr = [1, 2, 3, 4];
let value = 2;

if (!arr.includes(value)) {
  arr.push(value);
}

console.log(arr);

This will output [1, 2, 3, 4], because the value 2 already exists in the array.

If you want to add the value only if it’s not already in the array, you can use this code:

let arr = [1, 2, 3, 4];
let value = 5;

if (!arr.includes(value)) {
  arr.push(value);
}

console.log(arr);

This will output [1, 2, 3, 4, 5], because the value 5 does not exist in the array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply