1

I'm trying to sort an array, where its objects consist of a dynamic key of type number.

Now I want to sort the objects so that the numbers start from the smallest first -- the number I mean is the key of the object.

Here's my code

const arr = [{"3": 32}, {"1": 42}, {"5": 48}];

arr.sort((a,b) => {
  if (a < b) {
    return -1;
  }

  if (a > b) {
    return 1;
  }

  return 0;
});

console.log(arr);

The order of the objects should be:

[{"1": 42},{"3":32},{"5":48}]
trincot
  • 317,000
  • 35
  • 244
  • 286
Verdo Fanv
  • 35
  • 3
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Sheri Feb 17 '22 at 06:54
  • @Sheri No, that question is about sorting an array of objects by the _value_ of a fixed property, _lexicographically_. This question is about sorting an array of single-property objects by _key_, _numerically_. – Sebastian Simon Feb 17 '22 at 07:00
  • Duplicate target found on [this search page](/search?page=2&tab=Relevance&q=is%3aa%20sort%20url%3a%22Object%2fkeys%22). – Sebastian Simon Feb 17 '22 at 07:01

4 Answers4

4

You'll need to extract the keys... like with Object.keys:

const arr = [{"3": 32}, {"1": 42}, {"5": 48}];

arr.sort((a,b) => Object.keys(a)[0] - Object.keys(b)[0]);

console.log(arr);
trincot
  • 317,000
  • 35
  • 244
  • 286
1

use this and it should work

let arr = [{"3": 32}, {"1": 42}, {"5": 48}];

let getKey=(array)=> Object.keys(array)[0]

arr.sort((a,b) => (getKey(a) - getKey(b)))

console.log(arr)
Ridwan Ajibola
  • 873
  • 11
  • 16
1

This should work

const arr = [{"3": 32}, {"1": 42}, {"5": 48}];

arr.sort((a,b) => {
  const firstKey = Object.keys(a)[0]
  const secondKey = Object.keys(b)[0]
    return  secondKey - firstKey
})
Ahmed Mansour
  • 500
  • 4
  • 14
1

Not sure whether its perfect, but surely works.

const arr = [{"3": 32}, {"1": 42}, {"5": 48}];

const sortedArr = arr.sort((a,b) => {
  let aKey = parseInt(Object.keys(a)[0]);
  let bKey = parseInt(Object.keys(b)[0]);

  return aKey - bKey;
});

console.log(sortedArr);
Lakshaya U.
  • 1,089
  • 1
  • 5
  • 21