array map not last item in javascript

In order to map an array excluding the last item in Javascript, you can make use of slice method to create a new array with all the elements of the original array except the last one. Here's an example code snippet:

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

const modifiedArr = arr.slice(0, -1).map((item) => {
   // Perform required operations on each item except last item
   return item * 2;
});

console.log(modifiedArr); // Output: [2, 4, 6, 8]
222 chars
9 lines

In this code, arr.slice(0, -1) returns a new array with all elements except the last one. Then, .map() function is applied to each element of this new array to perform the required operations.

related categories

gistlibby LogSnag