5

I'm trying to use jQuery to create the below sample array I want to output:

[["foo0","foo1"],["foo2","foo3","foo4"],["foo5"]]

Code I'm trying to use:

var counter = 0;
var arr = [];
$('.unknown-number-of-elements').each(function(){
    var keyNumber = $(this).val();
    var valToPush = "foo"+counter;
    if(keyNumber in arr){
      arr[keyNumber].push(["'"+ valToPush +"'"]);
    }else{
      arr[keyNumber] = valToPush;
    }
    counter++;
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="unknown-number-of-elements" value="1">
<input class="unknown-number-of-elements" value="2">
<input class="unknown-number-of-elements" value="3">
<input class="unknown-number-of-elements" value="4">
<input class="unknown-number-of-elements" value="5">

The code above is giving the following error:

Uncaught TypeError: arr[keyNumber].push is not a function

Basically if the array key already exists I would like to create a sub array and add values to that sub array.

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
Austin
  • 1,619
  • 7
  • 25
  • 51
  • Check [this](https://stackoverflow.com/q/6356122/3551786), there is no `in` operator in javascript to check whether element is present in array or not. – Durga Jul 31 '18 at 13:17

1 Answers1

2

You never create the subarrays, you only put valToPush into the one array.

Do: arr[keyNumber] = [ valToPush ];, creating an array which contains your first value.

Or:

if ( !arr[ keyNumber ] ) {
    arr[ keyNumber ] = [];
}
arr[ keyNumber ].push( valToPush );
Ben West
  • 4,398
  • 1
  • 16
  • 16