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

Time:08-28

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

CodePudding user response:

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

CodePudding user response:

In one line:

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

CodePudding user response:

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)

  • Related