1

i create a let in JavaScript below format

  let  map={'431':232,'432':123,'433':120}

i want to order the map into following format. order by value.

map={'433':120,'432':123,'431':232}

at last i need to store index and value as numbers.

int1=431 // index as number

int2=232 // values as number
Phil
  • 128,310
  • 20
  • 201
  • 202
  • please look into this [link](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – gowridev Sep 29 '20 at 05:18
  • Check this https://stackoverflow.com/questions/9658690/is-there-a-way-to-sort-order-keys-in-javascript-objects – Krk Rama Krishna Sep 29 '20 at 05:19
  • Your question lacks focus on the part you have a problem with? Setting up the let? Doing the sorting? Determining the indexes? Storing them in variables (or better in an array)? You could fix that by providing a [mre] of what you already have and remove those things from the question you already have achieved. If the problem is with the frist part please remove the all other parts and only as about the first one. – Yunnosch Sep 29 '20 at 05:20

3 Answers3

2
  1. Convert the object to an entries array
  2. Sort it by key (entry[0])
  3. Grab the last entry by index or via Array.prototype.pop()

let map = {'431':232,'432':123,'433':120}

const sorted = Object.entries(map).sort(([ key1 ], [ key2 ]) =>
  key2 - key1)
  
const [ int1, int2 ] = sorted[sorted.length - 1]

console.info(int1, int2)
Phil
  • 128,310
  • 20
  • 201
  • 202
2

Use Object.entries, sort them and take the first element (using destructure)

let map = { '431': 232, '432': 123, '433': 120 };

const [[key, value]] = Object.entries(map).sort(([a], [b]) => +a - +b);

console.log(key, value);
Lioness100
  • 7,179
  • 5
  • 9
  • 43
Siva K V
  • 7,622
  • 2
  • 11
  • 24
0

it creates your goal object and what you want you can find.

let  map={'431':232,'432':123,'433':120}
var keys = [];
var values = [];
for(var k in map) keys.push(parseInt(k));

for(var v in map) values.push(map[v]);
values = values.sort().reverse();
let finalObj=[];
for(i=0;i<keys.length;i++){
  let obj = {};
  obj[keys[i]] = values[i];
  finalObj.push(obj)
}

console.log(finalObj[finalObj.length-1])
Mehrzad Tejareh
  • 591
  • 3
  • 17