how to get last time of values in array object nodejs

63 views Asked by At

I have an array objects of market ticks with the following values:

candles['AUDIOUSDT'] = [
    {
        t: 1649936820000,
        o: 41044.99,
        c: 41052.21,
        h: 41063.84,
        l: 41044.99,
        v: 1.2067
    },
    {
        t: 1649936820000,
        o: 41044.99,
        c: 41045,
        h: 41063.84,
        l: 41044.99,
        v: 1.3728
    },
    {
        t: 1649936880000,
        o: 41044.99,
        c: 41045,
        h: 41063.84,
        l: 41044.99,
        v: 0.1
    },
    {
        t: 1649936880000,
        o: 41044,
        c: 41049,
        h: 41049,
        l: 41011,
        v: 1
    }
]

and I would like to have last time of each time in array object:

candles['AUDIOUSDT'] = [
{
    t: 1649936820000,
    o: 41060.01,
    c: 41045,
    h: 41063.84,
    l: 41044.99,
    v: 1.3728
},
{
    t: 1649936880000,
    o: 41044,
    c: 41049,
    h: 41049,
    l: 41011,
    v: 1
}

Basically, I want to merge values if t, o, c, h, l, v which are the same time, any ideas on how to elegantly do this?

Thanks in advance

1

There are 1 answers

0
AudioBubble On BEST ANSWER

So, it just requires you to do a backwards loop and check if the "t" value is already in a unique times list. If it is, it will skip it, else it will add the entire object to a new uniques array which holds the results.

// where the unique times will be held
let unique_times = [];
// where the unique results will be held
let uniques = [];
// loop through the array backwards
for (var i = candles['AUDIOUSDT'].length; i--;) {
  // if current time in object is already in the unique_times array, skip over it
  if (unique_times.indexOf(candles['AUDIOUSDT'][i].t) > -1) {continue;}
  // adds the current time to this array, so the loop knows it's been added and doesn't count it again
  unique_times.push(candles['AUDIOUSDT'][i].t);
  // adds the current object to the new results
  uniques.push(candles['AUDIOUSDT'][i]);
}
// 'uniques' holds the filtered array of objects
console.log(uniques);