0

I have an object like such:

{ '2018':
   { '12':
      { '25': {},
        '26': {},
        '27': {},
        '28': {},
        '29': {},
        '30': {},
        '31': {} } },
  '2019': { '1': { '1': {} } } }

However for frontend purposes, I would like to reverse these values so it shows the most recent dates first. I know that Javascript can't guarantee the order of keys so this isn't even an ideal solution. What is the best way to represent this data so I can iterate over it on the frontend and display the data for each day properly? Thanks

Anthony
  • 13,434
  • 14
  • 60
  • 80
  • please share expected out structure. – Dipak Jan 03 '19 at 05:34
  • @Robert Harvey, that question doesn't deal with nested data, besides Javascript doesn't guarantee order with so it's not even a true answer there – Anthony Jan 03 '19 at 05:45
  • @RoberHarvey you did link this question to another closed question which is linked with the order of keys in an object. Maybe his goal was to have anyway a reverted strucutre (as an array) composed by objects in the opposite order – quirimmo Jan 03 '19 at 05:48
  • @quirimmo I've actually designed a solution I'll post it once I confirm it works – Anthony Jan 03 '19 at 05:50

1 Answers1

-2

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']

var reversed = array1.reverse(); 
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']

/* Careful: reverse is destructive. It also changes
the original array */ 
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']

OR

//non recursive flatten deep using a stack
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
  const stack = [...input];
  const res = [];
  while (stack.length) {
    // pop value from stack
    const next = stack.pop();
    if (Array.isArray(next)) {
      // push back array items, won't modify the original input
      stack.push(...next);
    } else {
      res.push(next);
    }
  }
  //reverse to restore input order
  return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]