0
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.

4 Answers 4

4

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] }
});
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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 }
  });

1 Comment

(you mean the documentation, not the implementation)
0

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

Comments

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.