HardRock
HardRock

Reputation: 1091

How to sort array of objects by dynamic proprety name?

I would appreciate your help or idea how to sort array of object in ascending order by first value.

This is array

[{"0":"yanni"},
{"1150":"finally"},
{"852":"discovered"},
{"59":"what"},
{"30064":"had"},
{"397":"really"},
{"3100":"happened"},
{"3":"to"},
{"0":"skura"},
{"7523":"lets"},
{"6550":"try"},
]

and I want to be sorted by first number like:

[{"0":"yanni"},
{"0":"skura"},
{"3":"to"},
{"59":"what"},
.....
]

I tried like this

const keys = Object.keys(sentenceFreq);
  console.log("key",keys)
  const valuesIndex = keys.map((key) => ({key, value: sentenceFreq[key]}));

  valuesIndex.sort((a, b) => b.value - a.value); // reverse sort

  const newObject = {};

  for (const item of valuesIndex) {
    newObject[item.key] = item.value;
  }
  console.log("test", newObject);

but they are sorted only by key values...

Any help is appericated. Thank you!

Upvotes: 1

Views: 49

Answers (2)

Andy
Andy

Reputation: 63524

Use sort. Grab the first element of the Object.keys of both a and b and coerce them to an integer, then return the new sort order.

const arr = [{"0":"yanni"},{"1150":"finally"},{"852":"discovered"},{"59":"what"},{"30064":"had"},{"397":"really"},{"3100":"happened"},{"3":"to"},{"0":"skura"},{"7523":"lets"},{"6550":"try"}];

arr.sort((a, b) => {
  const first = +Object.keys(a)[0];
  const second = +Object.keys(b)[0];
  return first - second;
});

console.log(arr);

Upvotes: 1

rohanraj
rohanraj

Reputation: 402

By default, the sort method sorts elements alphabetically. but in your case, you can get the keys and try sort numerically just add a new method that handles numeric sorts (shown below) -

let arr = [{
  "0": "yanni"
}, {
  "1150": "finally"
}, {
  "852": "discovered"
}, {
  "59": "what"
}, {
  "30064": "had"
}, {
  "397": "really"
}, {
  "3100": "happened"
}, {
  "3": "to"
}, {
  "0": "skura"
}, {
  "7523": "lets"
}, {
  "6550": "try"
}];

arr.sort(function(a, b) {
  const first = +Object.keys(a)[0];
  const second = +Object.keys(b)[0];
  return first - second
});

console.log(arr);

Upvotes: 0

Related Questions