Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Set from Array and remove original items in JavaScript

I have an Array with duplicate values.

I want to create a Set to get the distinct values of that array and remove or create a new Array that will have the same data MINUS the elements required to create the Set.

This is not just a matter of remove the duplicates, but remove a SINGLE entry of a each distinct value in the original array

Something like that works, but I wonder if there is a more direct approach:

let originalValues = [
  'a',
  'a',
  'a',
  'b',
  'b',
  'c',
  'c',
  'd'
];

let distinct = new Set(originalValues);
/*
distinct -> { 'a', 'b', 'c', 'd' }
*/

// Perhaps originalValues.extract(distinct) ??
for (let val of distinct.values()) {
  const index = originalValues.indexOf(val);
  originalValues.splice(index, 1);
}

/* 
originalValues -> [
  'a',
  'a',
  'b',
  'c'
];
*/
like image 868
Lucas Ricoy Avatar asked Jan 08 '17 14:01

Lucas Ricoy


People also ask

How can I remove a specific item from an array in JavaScript?

Combining indexOf() and splice() Methods Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.

How do you remove an element from an array array?

You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove.

How do I remove from an array those elements that exists in another array?

For removing one array from another array in java we will use the removeAll() method. This will remove all the elements of the array1 from array2 if we call removeAll() function from array2 and array1 as a parameter.

How do you add and remove items from an array?

The splice method can be used to add or remove elements from an array. The first argument specifies the location at which to begin adding or removing elements. The second argument specifies the number of elements to remove. The third and subsequent arguments are optional; they specify elements to be added to the array.


1 Answers

Use Array#filter in combination with the Set:

const originalValues = ['a', 'a', 'a', 'b', 'b', 'c',  'c', 'd'];

const remainingValues = originalValues.filter(function(val) {
  if (this.has(val)) { // if the Set has the value
    this.delete(val); // remove it from the Set
    return false; // filter it out
  }

  return true;
}, new Set(originalValues));



console.log(remainingValues);
like image 73
Ori Drori Avatar answered Sep 29 '22 03:09

Ori Drori