0

probably title is confusing, well i'm using .map on array which returns square root, and i want to add to new array "is root of"

var numbers=[4,9,16];

var root= numbers.map(Math.sqrt + 'is root of' + roots.indexOf());
console.log(root);

In this example i used indexOf , but that's not right. Thanks!

3

2 Answers 2

1

You wouldn't really want to say that it's the root of the index, you'd want to report back with the original value. However, in the following example, you can see that if you want the index, it's passed as a parameter to the map function

var numbers=[4,9,16];

var root= numbers.map(function (val, index){
  return Math.sqrt(val) + ' is root of ' + val
});
console.log(root);
0

map accepts a function, and that function receives the value and the index of the value (and the array reference, for that matter) as arguments.

So perhaps:

var numbers = [4, 9, 16];

var root = numbers.map(function(value) {
    return Math.sqrt(value) + ' is root of ' + value;
});
console.log(JSON.stringify(root));

Note I just used value. If you really wanted the index for some reason, it's the second argument the map callback receives:

var root = numbers.map(function(value, index) {
    return Math.sqrt(value) + ' is root of ' + value + ' which is index ' + index + ' in the array';
});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.