Home > database >  How to determine if it is the first or not in mapping an array in javascript
How to determine if it is the first or not in mapping an array in javascript

Time:12-28

I am using React in typeScript.

I want to change the background color of array[0] by mapping the acquired array data.

Is there a way to determine if it is the first in an array?

This is arrayList

Array:[{"createDt":"2022/12/27", "status":"aaa","operatorId":"001"}, {"createDt":"2022/12/28", "status":"bbb","operatorId":"002"}]

in JSX

Array.map((item, index) => {
let bgColorHeader = '#FFCCCC'
// ★ I want to change the background color only at the beginning of the array.<br>
 if (/////// ←This) bgColorHeader = '#FFFFFF'
 return (
  <TableBody key={index}>
   <TableRow>
    <TableCell
     sx = {{backgroundColor: {bgColorHeader} }}
    >
 )
})

CodePudding user response:

You can use the index

array.map((element, index) => { /* ... */ })

If index = 0 then this is the first element of array

let bgColorHeader = index === 0 ? '#FFFFFF' : '#FFCCCC'

CodePudding user response:

you can do like this let bgColorHeader = index === 0 ? '#FFFFFF' : '#FFCCCC'

added to ur code

Array.map((item, index) => {
let bgColorHeader = index === 0 ? '#FFFFFF' : '#FFCCCC'
 return (
  <TableBody key={index}>
   <TableRow>
    <TableCell
     sx = {{backgroundColor: {bgColorHeader} }}
    >
 )
})
  • Related