1

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!

1
  • It should be sorted by numbers from 0 and up so smallest number after 0 is 3 and then 59.. Commented Jun 22, 2021 at 2:38

2 Answers 2

1

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

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

2 Comments

thanks.. just correct first-second gives the correct results
Just subtracting will coerce the values.
0

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

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.