user742030
user742030

Reputation:

How to Get Last Value That Equals to X in json Array

I'm needing to get the 'num' value where the last 'observed' is equal to "observed" in the following response given below (eg the one before 'estimated').

The return updates the next 'estimated' to 'observed' every three hours and I need to display the updated 'num' value each time the API is requested.

Your help is greatly appreciated.

axios.get('http://url_to_api')
  .then(function (response) => {
   //do the magic here to get last observed val
    console.log(LAST_OBSERVED_VAL)
  })

The Response:

[  
  [  
    "time_tag",
    "num",
    "observed",
    "scale"
  ],
  [  
    "2019-01-16 18:00:00",
    "2",
    "observed",
    null
  ],
  [  
    "2019-01-16 21:00:00",
    "3",
    "observed",
    null
  ],
  [  
    "2019-01-17 00:00:00",
    "3",  // <-- Get this value
    "observed",
    null
  ],
  [  
    "2019-01-17 03:00:00",
    "2",
    "estimated",
    null
  ],
  [  
    "2019-01-17 06:00:00",
    "2",
    "estimated",
    null
  ],
  [  
    "2019-01-18 00:00:00",
    "2",
    "predicted",
    null
  ],
  [  
    "2019-01-18 03:00:00",
    "1",
    "predicted",
    null
  ],
]

Upvotes: 0

Views: 46

Answers (1)

Simon Hi
Simon Hi

Reputation: 3016

You can insert something like this magic:

var k, LAST_OBSERVED_VAL = '';
for (k = response.data.length-1; k >= 0; k--)
{
    if (response.data[k][2] == "observed")
    {
        LAST_OBSERVED_VAL = response.data[k][1];
        break;
    }
}

Upvotes: 1

Related Questions