Was it helpful?

Question

Sorting an associative array in ascending order - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects like this −

const people = [
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}  
];

We are required to write a JavaScript function that takes in one such array and sorts the array in place, according to the age property of each object in increasing order.

Therefore, the output should look something like this −

const output = [
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"},
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"}
];

Example

Following is the complete code −

const people = [
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}
];
const sorter = (a, b) => {
   return a.age - b.age;
};
const sortByAge = arr => {
   arr.sort(sorter);
};
sortByAge(people);
console.log(people);

Output

This will produce the following output in console −

[
   { id: 3, name: 'Christine', age: 20, gender: 'm', category: 'G' },
   { id: 2, name: 'Brandon', age: 25, gender: 'm', category: 'G' },
   { id: 4, name: 'Elena', age: 29, gender: 'W', category: 'M' },
   { id: 1, name: 'Andrew', age: 30, gender: 'm', category: 'G' }
]
raja
Published on 30-Sep-2020 17:51:04
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top