Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a collection to an array in javascript

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?

like image 758
wajiw Avatar asked Mar 01 '11 17:03

wajiw


People also ask

Is a collection an array JavaScript?

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.

How do you change a set to an array?

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.


1 Answers

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.

like image 138
user113716 Avatar answered Oct 13 '22 11:10

user113716