0

I'm trying to find a way to sort an array that has dynamic keys without Lowdash. Any suggestions?

I'm trying to sort by the field unix_start

"chart": [
  {
      "Nov 24, 2020": {
          "a": 1,
          "b": 0,
          "c": 0,
          "unix_start": 1606194000,
          "unix_end": 1606280400
      }
  },
  {
      "Nov 23, 2020": {
          "a": 0,
          "b": 2,
          "c": 1,
          "unix_start": 1606107600,
          "unix_end": 1606194000
      }
  },
  {
      "Nov 22, 2020": {
          "a": 0,
          "b": 0,
          "c": 0,
          "unix_start": 1606021200,
          "unix_end": 1606107600
      }
  },
}
  • If your keys will be unique, I'd nix the array and use a Object or Map. A Map maintains the order the items were inserted in. – mykaf Nov 24 '20 at 21:14
  • Does this answer your question? [Sorting an array of objects by property values](https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values) – pilchard Nov 24 '20 at 22:23

1 Answers1

5

You can use .sort:

const chart =  [
  {
      "Nov 24, 2020": {
          "a": 1,
          "b": 0,
          "c": 0,
          "unix_start": 1606194000,
          "unix_end": 1606280400
      }
  },
  {
      "Nov 23, 2020": {
          "a": 0,
          "b": 2,
          "c": 1,
          "unix_start": 1606107600,
          "unix_end": 1606194000
      }
  },
  {
      "Nov 22, 2020": {
          "a": 0,
          "b": 0,
          "c": 0,
          "unix_start": 1606021200,
          "unix_end": 1606107600
      }
  },
]

const sortedArray = chart.sort((a,b) => {
  const [valueOfA] = Object.values(a);
  const [valueOfB] = Object.values(b);
  return valueOfA.unix_start - valueOfB.unix_start;
});

console.log(sortedArray);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48