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?

1

3 Answers 3

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')
})
1
  • and it's possible to know which is the last?
    – Kit
    Commented Aug 23, 2019 at 13:11
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); });

2
  • 1
    Thank you Neel Rathod :)
    – Kit
    Commented Aug 23, 2019 at 13:13
  • 1
    @CatarinaBatista Happy to help Commented Aug 23, 2019 at 13:15
1
array.map((object, index) => {
  var position = index;
})
0

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