I am new to JavaScript and I'm doing some basic exercises. in my code I have a JSON saved in a String. I want to sort it by age attribute, and show the older employee first in my table, by default.
var employees = '{"employees":[ {"name":"Lucas","surname":"White", "email":"email@gmail.com", "age":31, "work":{"Company":"userCompany", "role":"userRole"}, "car":[ {"brand":"userCar", "model":"userCar", "year":"userCar", "bollo":"userCar"}, ]},
{"name":"Mary","surname":"userSurname", "email":"email@gmail.com", "age":29, "work":{"Company":"userCompany", "role":"userRole"}, "car":[ {"brand":"userCar", "model":"userCar", "year":"userCar", "bollo":"userCar"} ]}, ]}'
I thought about parsing the JSON employees into an object, in order to use the JS methods to compare its values, but I don't think I have the right answer yet.
function compare(a,b) {
const obj = JSON.parse(employees);
if ( a.age < b.age ){
return -1;
}
else if ( a.age > b.age ){
return 1;
} else {
return 0;}
var compared = obj.compare();
console.log(compared);
}
or...
function sortByAge(a,b){
const obj = JSON.parse(employees);
for(var i = 0; i < obj.employees.length; i++){
return parseInt (a.age) - parseInt (b.age);
}
var sortedByAge = obj.sortByAge();
console.log(sortedByAge);
}
Is there something I'm missing? Thank you.
Don't mix things. Write a comparator function:
function byAge(a,b) {
if (a.age < b.age) return -1;
else if (a.age > b.age) return 1;
else return 0;
}
parse the JSON
const obj = JSON.parse(employees);
sort it
obj.employees.sort(byAge);
console.log(obj);
Bonus: Generic comparator
function by(property) {
return function (a, b) {
if (a[property] < b[property]) return -1;
else if (a[property] > b[property]) return 1;
else return 0;
};
}
const obj = JSON.parse(employees);
obj.employees.sort(by('age'));
console.log(obj);
Bonus #2 Shorthand for sorting by number values:
function byAge(a, b) {
return a.age - b.age;
}
Works because the calculation naturally works out to values smaller than 0, greater than 0, or exactly zero, just like an if
/ else if
/ else
would.
// even shorter as am arrow function
obj.employees.sort((a, b) => a.age - b.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.