I'm trying to create an array in jquery. I need this array to have multiple other arrays in them.
My code now:
var arr = [];
$('.thumb').each(function(){
arr.push($(this).attr('data-storename'),$(this).attr('data-grid-item-id'));
});
This gives me just 1 array with all the data-storename's and data-grid-item-id's in it.
I want my array to look like :
0 [
0 => data-storename : (someinfo)
1 => data-grid-item-id : (someinfo)
]
1 [
0 => data-storename : (someinfo)
1 => data-grid-item-id : (someinfo)
]
and so on.
All my attempts end up being one single array, but just nested inside another array. Any help?
asked Sep 19, 2016 at 15:27
peter vries
1732 silver badges15 bronze badges
1 Answer 1
Firstly you can use map() to create the outer array. You can then return an array containing the two values you require from the map() handler function. Try this:
var arr = $('.thumb').map(function(){
return [[$(this).data('storename'), $(this).data('grid-item-id')]];
}).get()
answered Sep 19, 2016 at 15:30
Rory McCrossan
338k41 gold badges322 silver badges353 bronze badges
Sign up to request clarification or add additional context in comments.
12 Comments
Tushar
Don't you have to
return in the map()Rory McCrossan
@Tushar thanks. Wrote that in the description, then forgot to actually put it in the example XD
Tushar
Still,
return arr.push(... ==> return [..., ...]peter vries
i get the console arror : Uncaught TypeError: Cannot read property 'push' of undefined(anonymous function)
adeneo
tada ->
$.map($('.thumb'),e=>[[$(e).data('storename'), $(e).data('grid-item-id')]]); |
lang-js
arr.push([..., ...]);in theeach().Array.from($('.thumb'), function (el) { return [..., ...] })