简体   繁体   中英

How do I sort this data of people in ascending order of their age

const people = {
'1' : {'name' : 'Rohan', 'age' : 24},
'2' : {'name' : 'Ujjwal', 'age' : 27},
'3' : {'name' : 'Tara', 'age' : 18},
'4' : {'name' : 'Sagar', 'age' : 20},
'5' : {'name' : 'Kumar', 'age' : 21}

} people.sort(function(a, b){ return a.age - b.age;})

console.table(people);

Change to array and rebuild the object:

 const people = { '1': { 'name': 'Rohan', 'age': 24 }, '2': { 'name': 'Ujjwal', 'age': 27 }, '3': { 'name': 'Tara', 'age': 18 }, '4': { 'name': 'Sagar', 'age': 20 }, '5': { 'name': 'Kumar', 'age': 21 } } var a = [] for (let i in people) { a.push(people[i]) } a = a.sort((a, b) => a.age - b.age) const newPeople = {}; for (let i = 0; i < a.length; i++) newPeople[(i + 1).toString()] = a[i] console.log(people); console.log(newPeople);

Transform the object to an array and then sort it (the result will be an array though):

 const people = { '1': { 'name': 'Rohan', 'age': 24 }, '2': { 'name': 'Ujjwal', 'age': 27 }, '3': { 'name': 'Tara', 'age': 18 }, '4': { 'name': 'Sagar', 'age': 20 }, '5': { 'name': 'Kumar', 'age': 21 }, } const peopleSorted = Object.values(people).sort((a, b) => { return a.age - b.age }) console.log(peopleSorted)

In one line:

const sorted_people_asc = Object.values(people).sort((obj1, obj2) => obj1.age - obj2.age }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM