0

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
3
  • please look into this link Commented Sep 29, 2020 at 5:18
  • Check this stackoverflow.com/questions/9658690/… Commented Sep 29, 2020 at 5: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 minimal reproducible example 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. Commented Sep 29, 2020 at 5:20

3 Answers 3

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

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

Comments

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

Comments

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

3 Comments

how i can get the last key and value as number..?
I edit my answer to get last key and value. I hope it helps you. if you get help vote my answer.
did you test it ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.