Home > Blockchain >  Find first element of array and show it in map function but have warning - React
Find first element of array and show it in map function but have warning - React

Time:11-05

I have data like so:

    {
      "title": 0,
      "name": 0,
      "score": 0,
      "summary": [
        {
          "id": 1,
          "start": "2019-11-01",
          "end": "2019-11-04"
        },
        {
          "id": 2,
          "start": "2019-11-01",
          "end": "2019-11-04"
        }
      ]
    }

I am trying to access the first element of summary, so I have tried this:

    const newDate = new Date(data?.summary.map((d: any, index: number) => {
               if (index === 0) {
                 return (
                 new Date(d.start)
               )
          }
     })),

although it's working i get the warning:

Array.prototype.map() expects a value to be returned at the end of arrow function array-callback-return

I know it must be because I am not returning anything in the callback and the return is in the if statement?

CodePudding user response:

if (index === 0) {
                 return (
                 new Date(d.start)
               )

You are only returning a value if index === 0.

Im not sure what are you trying to achieve:

const newDate = new Date(data?.summary.map((d: any, index: number) => {
           if (index === 0) {
             return (
             new Date(d.start)
           )
      }
 })),

I suppose:

const newDate = newDate(data?.summary[0]?.start) 

Will do the thing.

CodePudding user response:

You can access to the first element without using map function:

const newDate = new Date(data?.summary[0].start)
  • Related