a1letterword
a1letterword

Reputation: 307

JavaScript Array not indexing properly?

var graphdata = [["A", "B", "C", "D"], [0.5, 0.25, 0.5, 0.25]];

function randomData (){
    var labels = graphdata[0]
    var labels2 = graphdata[1];
    console.log();
    return labels.map(function(labels, labels2){
        console.log(labels2);
        return { label: labels , value: labels2 }
    });
}

labels iterates correctly for A, B, C, D. but labels2 gets squashed to 0, 1, 2, 3, and I am not sure why. Right before the return labels.map() call, if I console.log(), I can get the properly fractions to output but after that those values disappear and I am not sure why.

Upvotes: 0

Views: 112

Answers (4)

Srishan Supertramp
Srishan Supertramp

Reputation: 395

Please read the documentation of map here. The callback to the map function takes two parameters, first being each item in the list that is to be iterated over, and second the index or key of that item in the list. The labels2 variable in your map callback doesn't refer to the one you created, it refers to the index of the item being mapped upon. Your implementation can be written as follows and it would be the same.

labels.map(function(eachLabel, key) {
    console.log(key); // 0, 1, 2, 3... (label.length - 1)
    return { label: eachLabel , value: key }
  });

Upvotes: 1

Roman
Roman

Reputation: 5210

The Array.map() takes a callback with the parameters for the current Element, current index (optional) and the original array (optional).

randomArray.map(function(currentElement, currentIndex, randomArrayAgain) { /*...*/})

You could do:

labels.map(function(label, index) {
    return { label: label, value: labels2[index] }
});

Explanaion

map() will iterate over labels and in each iteration you have access to the current label and index. This solution works only when your arrays are sorted in the right way.

Upvotes: 2

Mark
Mark

Reputation: 92440

map() doesn't work this way.

The second parameter to map() is the index of the element it is currently looking at. So each time through it sets the first parameter labels to the element from labels that it's currently mapping the sets labels2 to the index of labels.

Here's more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382132

The second argument given to the map callback is the index of the element in the iteration.

It looks like what you want would be

return labels.map(function(label, i){
    return { label: label , value: labels2[i] }
});

Upvotes: 4

Related Questions