skip to Main Content

have json object of which I would like to get the max value of showstopinfo :

var data = [{
  "info": [
    {
      "ticketinfooo": {
        "showstopinfo": 1
      }
    },
    {
      "ticketinfooo": {
        "showstopinfo": 6
      }
    }

  ]
}, {

  "info": [
    {
      "ticketinfooo": {
        "showstopinfo": 22
      }
    },
    {
      "ticketinfooo": {
        "showstopinfo": 23
      }
    }

  ]
}]

I`ve just written the code below but it return NAN value:

var max = Math.max(...data.map(e => e.info.map(x => x.ticketinfooo.stoppinfoo.showstopinfo)))
console.log(max)

What is wrong with this code?

2

Answers


  1. You need to map() on the outer array and also the inner info array. From there you’ll have a 2d array which you’ll need to flatten.

    Here’s a working example:

    var data = [{info:[{ticketinfooo:{showstopinfo:1}},{ticketinfooo:{showstopinfo:6}}]},{info:[{ticketinfooo:{showstopinfo:22}},{ticketinfooo:{showstopinfo:23}}]}];
    
    var values = data.map(d => [...d.info.map(i => i.ticketinfooo.showstopinfo)]).flat();
    var max = Math.max.apply(null, values);
    console.log(max)
    Login or Signup to reply.
  2. You have to add .flat() at the end of your array. Also x.ticketinfooo.stoppinfoo.showstopinfo should be x.ticketinfooo.showstopinfo.

    Math.max(...data.map(e => e.info.map(x => x.ticketinfooo.showstopinfo)).flat()) 
    >>> 23
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search