0

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'};
Shakil Ahmad
  • 143
  • 1
  • 2
  • 13
  • Why do you want to do this? – Andy Sep 11 '22 at 10:46
  • You can't; use a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instead. In an object, the property order is (ignoring inherited properties): Properties whose keys are [array indexes](https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#array-index) by their *numeric* value, followed by other string properties by the order in which the properties were created. Your keys are strings that match the definition of array indexes, so they'll always be iterated by their numeric. Value. In contrast, a `Map`'s entries are always... – T.J. Crowder Sep 11 '22 at 10:48
  • ...iterated strictly in the order they were created (and can actually have numbers as keys). So you can get your desired order by building the `Map` in the order you want, perhaps going through an array of arrays first to do the sorting: `const map = new Map(Object.entries(response).sort((a, b) => a[1].localeCompare(b[1]))); ` [fiddle](https://jsfiddle.net/tjcrowder/kw0Lcau2/). – T.J. Crowder Sep 11 '22 at 10:54

1 Answers1

1

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]);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • The result is correct but I need the format as the same as Obj. The output of your code adds square brackets to each index and value. the output should be E.g: {3: 'Ab', 8: 'Fe', 10: 'Bc', 15: 'Eg'}; – Shakil Ahmad Sep 12 '22 at 08:07
  • @ShakilAhmad you can simply cast it as edited above. – Majed Badawi Sep 12 '22 at 17:39