JavaScript(JS) JS remove duplicates from array

‮tth‬ps://www.theitroad.com

To remove duplicates from an array in JavaScript, you can use several approaches. Here are a few examples:

  1. Using a Set:
let arr = [1, 2, 3, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]

In this code, we use the Set object to create a new Set from the array arr. Sets only contain unique values, so any duplicates are automatically removed. Then we use the spread operator (...) to convert the Set back into an array.

  1. Using the filter() method:
let arr = [1, 2, 3, 3, 4, 4, 5];
let uniqueArr = arr.filter((value, index, self) => {
  return self.indexOf(value) === index;
});
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]

In this code, we use the filter() method to create a new array uniqueArr that only contains elements whose first occurrence matches their current index. We do this by using the indexOf() method to find the index of the current value in the original array arr, and then comparing it with the current index in the filter function.

  1. Using a for loop:
let arr = [1, 2, 3, 3, 4, 4, 5];
let uniqueArr = [];

for (let i = 0; i < arr.length; i++) {
  if (!uniqueArr.includes(arr[i])) {
    uniqueArr.push(arr[i]);
  }
}

console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]

In this code, we use a for loop to iterate over the array arr, and add elements to the uniqueArr array only if they are not already present in the uniqueArr. We do this by using the includes() method to check if the current element is already present in the uniqueArr.

All three of these methods produce the same output: an array containing only the unique elements from the original array.