Search code examples
javascriptlodash

Re-ordering object of arrays


I have an object composing of several arrays that share common properties for events in a time series:

{
  time: [1522513800000, 1522515600000, 1522517400000, 1522519200000]
  event: ['foo', 'bar', 'some', 'thing']
  notes: ['', 'not foo', 'sum', '']
}

I would like to re-order (re-arrange?) this object into an array of arrays of corresponding values, like so:

[[1522513800000, 'foo', ''], [1522515600000, 'bar', 'not foo'], [1522517400000, 'some', 'sum'], [1522519200000, 'thing', '']]

I prefer a vanilla / ES6 solution, but I am using lodash in this project if that works.


Solution

  • Convert it to an array first, and then use .sort:

    const input = {
      time: [1522513800000, 1522515600000, 1522517400000, 1522519200000],
      event: ['foo', 'bar', 'some', 'thing'],
      notes: ['', 'not foo', 'sum', '']
    };
    const numItems = input.time.length;
    const items = Array.from({ length: numItems }, (_, i) => ([
      input.time[i],
      input.event[i],
      input.notes[i],
    ]));
    items.sort((itemA, itemB) => itemB.time - itemA.time);
    console.log(items);