0

I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?

finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
    var temp = [];
    for(var j in $scope.team[i])
    {
        // counter = some value calculated here
        temp[j] = $scope.team[i][j][counter];
    }
    finalArray[group[i]] = temp; // This gives an error
}

basically, I have

group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically

my finalArray should be like,

finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....

As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out

3
  • 1
    If you want named keys instead of numeric indexes, then you want to use a Javascript object, not an array. Commented Jun 10, 2015 at 9:23
  • Object will work best Commented Jun 10, 2015 at 9:23
  • how do I declare it using Object? Commented Jun 10, 2015 at 9:38

3 Answers 3

1

You have to use Object instead of Array. Make the following changes in the code

finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
    var temp = {};
    for(var j in $scope.team[i])
    {
        // counter = some value calculated here
        temp[j] = $scope.team[i][j][counter];
    }
    finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure

now you can reference the values in finalArray with group[i] name. Hope this helps

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

Comments

1

You have to define your finalArray variable as Object instead of and Array:

var finalArray = {}; //or better in your case finalMap

Comments

1
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
    finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);  

DEMO

1 Comment

you should check if ( gorup.hasOwnProperty(index) ) {...} to prevent undesidered behaviour.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.