0

Given the html

<div class="recipeList">
  <div class="recipe" data-id="abc"></div>
  <div class="recipe" data-id="def"></div>
  <div class="recipe" data-id="ghi"></div>
  <div class="recipe" data-id="jkl"></div>
</div>

and the jQuery

$('.recipeList').find('.recipe')
      .map(function(index, element) {
        return [
          $(element).data('id'),
          { sequence: index }
        ]
       }).get()

I would expect to get

[
  ['abc',{sequence:0}],
  ['def',{sequence:1}],
  ['ghi',{sequence:2}],
  ['jkl',{sequence:3}]
]

but instead I get

[
  'abc',
  {sequence:0},
  'def',
  {sequence:1},
  'ghi',
  {sequence:2},
  'jkl',
  {sequence:3}
]

Is there a way to map a jQuery's selected elements to a 2d array, i.e., how can I get the expected output?

(Obviously I can manipulate the 1d array returned by .map(), to generate my expected output, but I'd rather not, and I'm also curious about this behavior of .map(): why is it producing this result, and is there a way to get it to return a 2d array instead?)

Aaron Dunigan AtLee
  • 1,860
  • 7
  • 18
  • 1
    Can you return an array of arrays from your map? I’d strongly recommend getting off Jquery – Daniel A. White Jan 24 '23 at 01:00
  • Vanilla JS version... `Array.from(document.querySelectorAll(".recipeList .recipe"), (el, sequence) => [el.dataset.id, { sequence }])` – Phil Jan 24 '23 at 03:43

1 Answers1

-1
$('.recipeList').find('.recipe').map(function (index, element) {
    return [[$(element).data("id"), { sequence: index }]];
}).get();

This will give you the result you want. My logic is that the .map() function already returns a new array because that's the purpose of it, so returning a single array is redundant. Therefore, by wrapping each data set in an array (within the parent array), you'll get arrays inside of an array.

Sorry I don't have a better explanation, but if it works it works. ¯\(ツ)

Mark Hillard
  • 202
  • 3
  • 9
  • The _explanation_ is that it is by design in jQuery (to many complaints)... [_"A returned array will be flattened into the resulting array"_](http://api.jquery.com/jquery.map/) – Phil Jan 24 '23 at 03:52
  • Thanks for your expert assistance Phil. – Mark Hillard Jan 24 '23 at 03:55
  • My mistake, you're correct... but according to https://stackoverflow.com/help/privileges/vote-down, there are alternatives to voting down, like actually being helpful. When he asked "is there a way to get it to return a 2d array instead", I provided an answer. – Mark Hillard Jan 24 '23 at 04:01