How to sort indexed object by alphabetical value in javascript

Viewed 28

I have an indexed object and need to sort it by alphabetic value. I tried sort() function but it remove the given indexes and assign new indexes starting from 0, and I want to keep the existing indexes but just sort by the value.

Here is my code.

var response = {3: 'Ab', 8: 'Fe', 10: 'Bc', 15: 'Eg'}; 
var sorted = Object.values(response).sort();

sorted output = {Ab, Bc, Eg, Fe} but I don't want to change the existing indexes of each value.

I need to sort the object like this.

var sorted = {3: 'Ab', 10: 'Bc', 15: 'Eg', 8: 'Fe'};
1 Answers

Using an object for your case will not work since the ordering will be by the numeric keys, I suggest you use a Map as follows:

const obj = {3: 'Ab', 8: 'Fe', 10: 'Bc', 15: 'Eg'}; 

const sorted = Object
  .entries(obj)
  .sort(([, a], [, b]) => a.localeCompare(b))
  .reduce((map, [key, value]) => map.set(+key, value), new Map);

console.log([...sorted]);

Related