user820304
user820304

Reputation:

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.

Upvotes: 0

Views: 46

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370809

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);

Upvotes: 2

Related Questions