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
      }
  },
}
2
  • 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. Commented Nov 24, 2020 at 21:14
  • Does this answer your question? Sorting an array of objects by property values Commented Nov 24, 2020 at 22:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.