1

I have an array of data that is returned to me from a CMS. I map over each item and return a component with the corresponding data. However, I need to target the last item in the .map function in the render method as the last item needs some modification.

How would I do this?

return (
  <div>
    {data.body.map((item, i) => {
      console.log(i);
      if (item.type === 'button') {
        return <ButtonComponent color="ffffff" bgColor="4C319D" text={item.text} textAlign="left" id={item.id} />
      }
    })}
  </div>
)
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
  • Does this answer your question? [Get the last item in an array](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – Danila Feb 22 '21 at 10:30

2 Answers2

7

Test the index against the length of the array.

const array = ['a', 'b', 'c', 'd'];

const mapped = array.map(
    (value, index, array) => {
        if (array.length - 1 === index) {
            console.log(`${value} is the last item in the array`);
            return `-->${value.toUpperCase()}<--`;  
        } else {
            return value.toLowerCase();  
        }
    } 
);

console.log({mapped});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

generally for access to the last item in array you can use this Formula:

const myArray = [1,2,3,4];

myArray[myArray.length - 1] // return 4.

and in your code you can use this way:

<div>
      {data.body.map((item, i) => {
        console.log(i);
        if (item.type === 'button') {
          return <ButtonComponent color="ffffff" bgColor="4C319D" text={item.text} textAlign="left" id={item.id} />
        }
        const lastItem = data.body[data.body.length - 1]
      })}


    </div>