How to Avoid Adding Duplicates to an Array in JavaScript?

Estimated read time 1 min read

One way to avoid adding duplicates to an array in JavaScript is to check if an item already exists in the array before adding it. One approach is to use the Array.includes() method, which returns a Boolean indicating whether an element is present in an array:

let myArray = [1, 2, 3, 4];
let newItem = 3;

if (!myArray.includes(newItem)) {
  myArray.push(newItem);
}

Another approach is to use the Array.indexOf() method, which returns the first index of an element in an array, or -1 if it is not present:

let myArray = [1, 2, 3, 4];
let newItem = 3;

if (myArray.indexOf(newItem) === -1) {
  myArray.push(newItem);
}

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply