-1

I am trying to convert my answer in an object because it is showing an array in the console?

This is my object

const myObject = {0: 54,1: 77,2: 79,3: 39,4: 37,5: 15,6: 23,7: 2,8: 4,9: 8,s: 439,k: 84,i: 654,p: 441,t: 954,o: 799,m: 236,a: 936,n: 675,c: 556,e: 1211,l: 597,g: 117,u: 596,r: 973,h: 200,f: 239,d: 284,b: 176,y: 281,w: 88,v: 174,j: 53,x: 79,'[': 65,']': 65,q: 11,_: 32,z: 3,};

Here I sort the object according to values:

const myObject = {0: 54,1: 77,2: 79,3: 39,4: 37,5: 15,6: 23,7: 2,8: 4,9: 8,s: 439,k: 84,i: 654,p: 441,t: 954,o: 799,m: 236,a: 936,n: 675,c: 556,e: 1211,l: 597,g: 117,u: 596,r: 973,h: 200,f: 239,d: 284,b: 176,y: 281,w: 88,v: 174,j: 53,x: 79,'[': 65,']': 65,q: 11,_: 32,z: 3,};

const finalAns = Object.entries(myObject).sort(function (a, b) {
  return b[1] - a[1];
});

console.log(finalAns);

This is my output of consol.log.

I am getting finalAns as an Array, but I want to print answer as an object and the object should be sorted according to its values?

Ankit Sahu
  • 13
  • 4
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort Sort takes an array, sorts it, then returns an array. – Lee Taylor Jan 23 '23 at 10:25
  • 1
    There is no concept of order (sorting) in normal objects. If you want to have a proper order, the only way to do it is through [iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#built-in_iterables), which includes Array, Map, Set, String, and more. – yqlim Jan 23 '23 at 11:22

1 Answers1

0

My understanding is that you are getting the correct answer, but you want to convert it to an object? If so, you could:

var finalAnsObject = JSON.stringify(finalAns)

Updated way (getting a javascript object, not a JSON string):

const newObject = Object.assign({}, ...finalAns.map(element => ({ [element[0]]: element[1] })));