-1

I have a javascript object which looks like the following:

{ john:32, elizabeth: 29, kevin: 30 }

This is an object with some names and ages.

How can I transform the object to array and sort the array by age?

I want it to be something like [{john:32}, {elizabeth:29}....]

georg
  • 211,518
  • 52
  • 313
  • 390
manolios
  • 11
  • 5

5 Answers5

1

I'd probably use Object.entries to convert the object to an array, then use the array sort method to do the sorting, and then reduce to reformat the array. See below.

const people = { john:32, elizabeth:29, kevin:30 };

const sorted = Object.entries(people).sort(
  (a, b) => a[1] - b[1]
).reduce((acc, [key, val]) => {
  acc.push({[key]: val});
  return acc;
}, []);

console.log(sorted);
Nick
  • 16,066
  • 3
  • 16
  • 32
1

1 line solution

console.log( Object.values({john:32, elizabeth:29, kevin:30}).sort((a, b)=>a - b) )

If you want array of objects

const obj = { john: 32, elizabeth: 29, kevin: 30 }

console.log(
    Object.keys(obj)
    .map(key=>({[key]: obj[key]}))
)
1

You can use Array.reduce to loop over the object keys to calculate the final result.

let peopleObject = {john: 32, elizabeth: 29, kevin: 30};
let result = Object.keys(peopleObject).reduce((rs, el) => {return [...rs, {[el]: peopleObject[el]}]; }, []).sort((a,b) =>Object.values(a)[0] - Object.values(b)[0])
console.log(result);
Linh Nguyen
  • 925
  • 1
  • 10
  • 23
0
//declaration
var myArray = [];
var myObject = {john:32, elizabeth:29, kevin:30};

//pushing the object in to an array
for (var key in myObject) {
     myArray.push([key, myObject[key ]]);
}

//sorting function
myArray.sort(function(a, b) {
   return a[1] - b[1];
});

//the above function returns the sorted array as
//elizabeth,29,kevin,30,john,32


//to create the sorted object from array
var objSorted = {}
myArray.forEach(function(item){
  objSorted[item[0]]=item[1]
});

//final output
//{elizabeth: 29, john: 32, kevin: 30}
Sasi Kumar M
  • 2,440
  • 1
  • 23
  • 23
0

This should work for your case

var obj = { john:32, elizabeth:29, kevin:30 };

    var rs = Object.keys(obj).reduce((rs, el) => {let b= {}; b[el] = obj[el];rs.push(b); return rs; }, []).sort((a,b) =>Object.values(a)[0] - Object.values(b)[0])
    console.log(rs)
js_user
  • 21
  • 4