Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove set of values in an existing Set

In JavaScript, I have the following Sets:

var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);

I need a function that removes a set of values:

removeAll(mySet, valuesToRemove);
// expected value of mySet: Set ["bar"]

// or a function that returns a new Set
var myNewSet = removeAll(mySet, valuesToRemove);
// expected value of myNewSet: Set ["bar"]

Question: Does any ES6-modules-compatible library exists that does the trick?

Lodash has a similar function for Arrays, but supporting JavaScript builtin iterable is tagged as wontfix. And I prefer to avoid doing multiple Array↔Set/Set↔Array conversions.

Alternatively, I will write my own function.

like image 706
Morgan Courbet Avatar asked Sep 27 '16 09:09

Morgan Courbet


3 Answers

It is much easier to write your own function than use a library for a single lightweight functionality:

var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);

function removeAll(originalSet, toBeRemovedSet) {
  [...toBeRemovedSet].forEach(function(v) {
    originalSet.delete(v); 
  });
}

console.log([...mySet]);
removeAll(mySet, valuesToRemove);
console.log([...mySet]);

I have used ES6 syntax since you use ES6, according to your question.
You can this function in a static class like SetUtility for your convenience.

like image 89
Yeldar Kurmangaliyev Avatar answered Sep 29 '22 08:09

Yeldar Kurmangaliyev


You could use Set#forEach directly with the set and delete then the value from the other set.

var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);

function removeAll(originalSet, toBeRemovedSet) {
    toBeRemovedSet.forEach(Set.prototype.delete, originalSet);
}

console.log([...mySet]);
removeAll(mySet, valuesToRemove);
console.log([...mySet]);
like image 29
Nina Scholz Avatar answered Sep 29 '22 08:09

Nina Scholz


You can use for..of loop .delete()

var removeAll = (keys, arr) => {for (prop of keys) arr.delete(prop); return arr};
removeAll(valuesToRemove, mySet); // `Set [ "bar" ]`
like image 28
guest271314 Avatar answered Sep 29 '22 06:09

guest271314