erasmo carlos
erasmo carlos

Reputation: 682

JavaScript: flatten an array without using reduce library

I have a nested array named $scope.instruments, its contents are:

collapsed:

enter image description here

expanded:

enter image description here

I also have an object:

enter image description here

This object contains 2 arrays: AttributeID and SPAttributeRefID.

Currently I am flattening the $scope.instruments array using reduce function:

$scope.instruments = $scope.instruments.reduce(function (result, instrument) {
    result[instrument.ID] = instrument;
    return result
}, {});

Then I access the AttributeID of the object and assign it to a variable like this:

$scope.recordInstrument = $scope.instruments[data.AttributeID[0]].ID;

I would rather use a different method to obtain the same result. I read that an array can be flatten using a for loop, that it is a more efficient method of doing it. Unfortunately, what I have tried so far, is not giving me the same results.

var arrInstruments = $scope.instruments;
var arrLength = arrInstruments.length;

for (var i = 0; i < arrLength; i++) {
    console.log(arrInstruments[i]);                                
}

Can someone give me a hand converting the code that uses the reduce function to use a loop and have the same result in the assignment of AttributeID?

Many thanks.

Upvotes: 0

Views: 393

Answers (1)

Dekel
Dekel

Reputation: 62556

This code should do what you are looking for:

var arrInstruments = $scope.instruments;
var arrLength = arrInstruments.length;
var result = {}
for (var i = 0; i < arrLength; i++) {
    result[arrInstruments[i].ID] = arrInstruments[i];
}
// the result variable contains what you want.

However I really don't understand why you would want that.

This screenshot you took:
enter image description here

Is not a multidimensional array. It's only the way your console show you a very large array (so it will not need to "draw" everything).

Upvotes: 3

Related Questions