简体   繁体   中英

Array.map : get the index of each element to use in the return function

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.

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() 

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]) 

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM