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.