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!

slawckaJS
  • 61
  • 1
  • 1
  • 6
  • 2
    Array.prototype.map takes a function as a parameter, which returns the new value for each element in the array. Try passing in a function that does the mapping. The function receives item, index, and array as parameters. – Travis Schettler Feb 02 '16 at 17:20
  • 1
    [MDN is your friend.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Mapping_an_array_of_numbers_using_a_function_containing_an_argument) – Mike Cluck Feb 02 '16 at 17:24
  • Possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Justin Feb 02 '16 at 18:00

2 Answers2

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);
jmcgriz
  • 2,819
  • 1
  • 9
  • 11
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';
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875