check last item in an array map function in javascript

To check the last item in an array's map function, you can use the indexOf function to compare the current index being looped over to the length of the array minus one, which is the index of the last item in the array. Here's an example:

index.tsx
const arr = [1, 2, 3, 4, 5];

const newArr = arr.map((item, index) => {
  if (index === arr.length - 1) {
    console.log("This is the last item in the array: " + item);
  }
  
  return item * 2;
});
200 chars
10 lines

In this example, we're looping over the original arr array using the map function. We pass in a callback function with two arguments: the current item being looped over (item) and the index of that item in the array (index).

Inside the callback function, we check if the index is equal to the length of the arr array minus one. If it is, then we know that the current item being looped over is the last item in the array, so we log out a message indicating this ("This is the last item in the array: " + item).

Regardless of whether or not the item is the last one in the array, we then multiple the item by 2 and return it to create a new newArr array.

gistlibby LogSnag