How to Find and Remove Duplicate Elements in a JavaScript Array Using IndexOf?

Estimated read time 1 min read

To find and remove duplicate elements in a JavaScript array using indexOf, you can create a new array and use a loop to iterate through the original array, checking if each element is in the new array. If it’s not, you can add it to the new array.

Here’s an example:

function removeDuplicates(arr) {
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (newArr.indexOf(arr[i]) === -1) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

let arr = [1, 2, 3, 1, 2, 3];
let newArr = removeDuplicates(arr);
console.log(newArr);

In this example, the code defines a function removeDuplicates that takes an array arr as an argument. The function creates a new array newArr and uses a for loop to iterate through the original arr array. For each element in the arr array, the code uses the indexOf method to check if the element is in the newArr array. If the element is not in the newArr array, the code adds it to the newArr array using the push method. The newArr array is then returned and logged to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply