-1

How can I sort data by age values?

var date = {
    michael : { color : "A", age : 30 },
    peter : { color : "C", age : 10 },
    martin : { color : "D", age : 7 },
    mario : { color : "R", age : 20 },
};

I want to get the following effect:

/*martin : { color : "D", age : 7 },
    peter : { color : "C", age : 10 },
    mario : { color : "R", age : 20 },
    michael : { color : "A", age : 30 }
*/
Umbro
  • 1,984
  • 12
  • 40
  • 99

2 Answers2

2

I think there is a misunderstanding of how objects work in JavaScript. Objects have a set of properties. Each property may have a value.

Properties don't have any particular order.

Think about it this way.

let x = {};
x.foo = 'hello';
y.bar = 'whats up?';
x.foo = 'world';

What order are the keys in? See, the question does not really make sense.

When you express an object literal like you did, you aren't implying any particular order.

var date = {
    michael : { color : "A", age : 30 },
    peter : { color : "C", age : 10 },
    martin : { color : "D", age : 7 },
    mario : { color : "R", age : 20 },
};

Is identical to

date.michael = { color : "A", age : 30 };
date.peter = { color : "C", age : 10 };
date.martin = { color : "D", age : 7 };
date.mario = { color : "R", age : 20 };

Maybe put more concisely, the order in which the lines in your source code appear does not really affect the object. It's like saying it has michael and peter, not, a list (michael, peter).

So what you are asking, in the most literal sense, is not possible. You can't sort an object's keys because they have no order any way. It's like sorting a car.

Now, if this were an array of objects, and each object had a property called name, this would be easy. Why? Arrays have an order. Arrays are by definition an ordered list of values.

var people = [
    { name: "michael", color : "A", age : 30 },
    { name: "peter", color : "C", age : 10 },
    { name: "martin", color : "D", age : 7 },
    { name: "mario", color : "R", age : 20 },
];

people.sort((a, b) => b.age - a.age);

will result in

[
    { name: "martin", color : "D", age : 7 },
    { name: "peter", color : "C", age : 10 },
    { name: "mario", color : "R", age : 20 },
    { name: "michael", color : "A", age : 30 },
]

Detailed documentation on Array.prototype.sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Brandon
  • 9,822
  • 3
  • 27
  • 37
0

This is correct answer:

var date = {
    michael : { color : "A", age : 30 },
    peter : { color : "C", age : 10 },
    martin : { color : "D", age : 7 },
    mario : { color : "R", age : 20 },
};


var sortedDataByAge = Object.keys(date)
.map(e => ({name:e, ...date[e]}))
.sort((a,b) => a.age - b.age)

console.log(sortedDataByAge)