Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array to Set

MSDN references JavaScript's Set collection abstraction. I've got an array of objects that I'd like to convert to a set so that I am able to remove (.delete()) various elements by name:

var array = [     {name: "malcom", dogType: "four-legged"},     {name: "peabody", dogType: "three-legged"},     {name: "pablo", dogType: "two-legged"} ]; 

How do I convert this array to a set? More specifically, is it possible to do this without iterating over the above array? The documentation is relatively lacking (sufficient for instantiated sets; not for conversions - if possible).

I may also be thinking of the conversion to a Map, for removal by key. What I am trying to accomplish is an iterable collection that can be accessed or modified via accessing the elements primarily via a key (as opposed to index).

Conversion from an array to the other being the ultimate goal.

like image 314
Thomas Avatar asked Mar 10 '15 13:03

Thomas


People also ask

Can you add an array to a Set in JavaScript?

To add an array of values to an existing Set :Use the forEach() method to iterate over the array. On each iteration use the add() method to add the array element to the Set . After the last iteration, all values from the array will be added to the Set .

How do you change an array in JavaScript?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new array.


2 Answers

Just pass the array to the Set constructor. The Set constructor accepts an iterable parameter. The Array object implements the iterable protocol, so its a valid parameter.

var arr = [55, 44, 65]; var set = new Set(arr); console.log(set.size === arr.length); console.log(set.has(65));

See here

like image 151
levi Avatar answered Oct 23 '22 04:10

levi


If you start out with:

let array = [     {name: "malcom", dogType: "four-legged"},     {name: "peabody", dogType: "three-legged"},     {name: "pablo", dogType: "two-legged"} ]; 

And you want a set of, say, names, you would do:

let namesSet = new Set(array.map(item => item.name)); 
like image 38
Ryan Shillington Avatar answered Oct 23 '22 02:10

Ryan Shillington