1

I'm looking for a command that returns the index of an element so I can use it in map functions.

Here's an example :

function myFunction() {
  var a = [4,7,9];
  //Looking for a way to return ["index 0 : 4", "index 1 : 7", "index 2 : 9"]
  //Only workaround found so far :
  var i = -1;
  Logger.log(a.map(function(el) {i++; return "index " + i + " : " + el}));
}

I'm sure there's a neater way with a command that would give me the element's index, but all my google searches have been fruitless so far.

Mike
  • 53
  • 1
  • 1
  • 6

4 Answers4

4

You can make it cleaner by three steps:

  • Use the second parameter of callback passed to map() which is index of element.
  • Use arrow function and implicitly return the value
  • Use Template Strings instead of + again and again.

var a = [4,7,9];
let res = a.map((x,i) => `index ${i} : ${x}`);
console.log(res)

In your above code you have created a function which doesn't make any sense. That function should take an array as a parameter and then log the value of that particular arr.

const myFunction = arr => console.log(arr.map((x,i) => `index ${i} : ${x}`));
myFunction([4,7,9])
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
2

Second parameter in callback function is index you can use that

  Array.map((value,index,this))

function myFunction() {
  var a = [4,7,9];
  console.log(a.map((v,i)=> "index " + i + " : " + v));
}

myFunction()
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

map already gives you the index. The callback gets three parameters:

a.map(function(element, index, array) {return "index " + index + " : " + element})

You don't need to declare all three (JavaScript isn't fussy about it), but they are there if you need them.

Amadan
  • 191,408
  • 23
  • 240
  • 301
1

You could also simply use Array.from since its second argument is an Array.map:

console.log(Array.from([4,7,9], (x, i) => `index ${i} : ${x}`))

The overall idea is to use the 2nd parameter of map (which provides you with the current iteration index) and with that and the current value to construct your result.

Akrion
  • 18,117
  • 1
  • 34
  • 54