-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}....]

4
  • Can you give an example of what you'd like the output array to look like? Commented Nov 16, 2019 at 16:22
  • Sorry about that I wanted to be something like [{john:32},{elizabeth:29}....] Commented Nov 16, 2019 at 16:24
  • Sorry dev_junwen but because I am new to js can you explain your answer a lit bit more. Commented Nov 16, 2019 at 16:27
  • What have you tried, and what exactly is the problem with it? Commented Nov 16, 2019 at 17:18

5 Answers 5

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

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

2 Comments

You are genious. Thank you. I was really struggling with this. I will upvote you.
No problem, happy to help!
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]}))
)

Comments

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

Comments

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}

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.