remove duplicates from an arrya

 

To remove duplicate values from an array, you can use various approaches. Here are a couple of common methods:

  1. Using the filter() method and the indexOf() method:

 s

function removeDuplicates(arr) {
  return arr.filter(function(value, index, self) {
    return self.indexOf(value) === index;
  });
}

var array = [1, 2, 3, 4, 3, 2, 5, 6, 1];
var uniqueArray = removeDuplicates(array);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]

s

  1. In this example, the removeDuplicates function uses the filter() method to create a new array that includes only the elements for which the callback function returns true. The callback function checks if the index of the current element value in the original array is equal to the first occurrence of that element in the array. If they are equal, it means the element is unique, and it is included in the new array.

  2. Using the Set data structure:

 s

function removeDuplicates(arr) {
  return Array.from(new Set(arr));
}

var array = [1, 2, 3, 4, 3, 2, 5, 6, 1];
var uniqueArray = removeDuplicates(array);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]

s


  1. In this example, the removeDuplicates function creates a Set using the input array. The Set automatically removes duplicate values since it only allows unique values. Then, Array.from() is used to convert the Set back into an array, resulting in an array with only unique values.

Both methods provide the same result, which is a new array containing only the unique values from the original array.


No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...