1

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?

3
  • 1
    arr.push([..., ...]); in the each(). Commented Sep 19, 2016 at 15:29
  • If you want to push an array, you need to push an array. Commented Sep 19, 2016 at 15:45
  • IMO, avoid broken, standards-defying APIs. JS now handles Array-like objects anyway. Array.from($('.thumb'), function (el) { return [..., ...] }) Commented Sep 19, 2016 at 15:52

1 Answer 1

2

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()

Working example

Sign up to request clarification or add additional context in comments.

12 Comments

Don't you have to return in the map()
@Tushar thanks. Wrote that in the description, then forgot to actually put it in the example XD
Still, return arr.push(... ==> return [..., ...]
i get the console arror : Uncaught TypeError: Cannot read property 'push' of undefined(anonymous function)
tada -> $.map($('.thumb'),e=>[[$(e).data('storename'), $(e).data('grid-item-id')]]);
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.