3

When you use for function you can save the position of an object like (example):

for (var i = 0; i < array.length; i++) {
    var position = i;
}

but I don't know how I can get the position an how I can know if it is the last using map function

array.map((object) => {
})

Someone can help?

ROOT
  • 11,363
  • 5
  • 30
  • 45
Catarina
  • 359
  • 3
  • 16
  • 6
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – tkausl Aug 23 '19 at 13:03

3 Answers3

7

The second parameter for the function provided to map is the current index of the element

arr.map((item, index) =>{
    if(index === arr.length-1) 
        console.log('last one')
})
Dupocas
  • 20,285
  • 6
  • 38
  • 56
2

In every of array methods (map(), forEach() etc..), the second parameter is an index of an array.

const array1 = [1, 2, 3];
array1.map((value, i) => { console.log(i); });

const array2 = [1, 2, 3];
array2.forEach((value, i) => { console.log(i); });
Neel Rathod
  • 2,013
  • 12
  • 28
1
array.map((object, index) => {
  var position = index;
})
Jackkobec
  • 5,889
  • 34
  • 34