I'm trying to figure out how to convert a javascript collection (i.e. something returned from getElementsByTagName/etc) to a normal array so I can perform array functions on the data.
I'm looking for a solution without using any libraries and haven't been able to find any sort of elegant solutions anywhere online. Has anyone written a good util function for this problem?
Indexed Collections (Arrays) arrays is the indexed collection in javascript. Array is an ordered set of values that has a numeric index and value. For example, you could have an array called employees that contains employees' names indexed by their numerical employee number.
Create a Set object. Add elements to it. Create an empty array with size of the created Set. Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it.
You can do this:
var coll = document.getElementsByTagName('div'); var arr = Array.prototype.slice.call( coll, 0 );
EDIT: As @Chris Nielsen noted, this fails in IE pre-9. Best would be to do some feature testing, and create a function that can handle either, or just do a loop as in the (second) solution from @brilliand.
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