I have below array of objects in javascript
[
{'name' : 'Ram', 'age': 10 , 'city' : 'a'},
{'name' : 'Shyam', 'age': 5 , 'city' : 'a'},
{'name' : 'Aditya', 'age': 10 , 'city' : 'b'},
{'name' : 'Aditya', 'age': 5 , 'city' : 'a'}]
Now I am in need to apply nested sorting.
A user could sort the above collection by name, age, city.
Suppose User asks to sort by name, the sorted array would look alike.
[
{'name' : 'Aditya', 'age': 5 , 'city' : 'a'},
{'name' : 'Aditya', 'age': 10 , 'city' : 'b'}
{'name' : 'Mohan', 'age': 50 , 'city' : 'b'}
{'name' : 'Ram', 'age': 10 , 'city' : 'a'}]
Now User clicks on to sort by age (asc), but it should not disturb the above array.
It should look alike
[
{'name' : 'Aditya', 'age': 5 , 'city' : 'a'},
{'name' : 'Aditya', 'age': 10 , 'city' : 'b'}
{'name' : 'Ram', 'age': 10 , 'city' : 'a'},
{'name' : 'Shyam', 'age': 5 , 'city' : 'a'}]
But if suppose user asks to sort the above sort desc by age so it should look alike
[
{'name' : 'Aditya', 'age': 10 , 'city' : 'a'},
{'name' : 'Aditya', 'age': 5 , 'city' : 'b'}
{'name' : 'Ram', 'age': 10 , 'city' : 'a'},
{'name' : 'Shyam', 'age': 5 , 'city' : 'a'}
This is how my current function to sort looks alike.
let compareObjects = (key, order = 'asc') => {
return function (a, b) {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
const varA = (typeof a[key] === 'string') ?
a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string') ?
b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order == 'desc') ? (comparison * -1) : comparison
);
}}
arrOfObjects.sort(compareObjects('age'));
But I have no clue how can I apply nested sorting?
Thanks!