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.
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 .
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.
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With