Created
May 28, 2020 20:00
-
-
Save alex-hladun/298ab110fcb38bd27d96aa15cf1b92d5 to your computer and use it in GitHub Desktop.
Sort through an array of objects using a specified sort function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const students = [ | |
{ id: 1, name: "bruce", age: 40 }, | |
{ id: 2, name: "zoidberg", age: 22 }, | |
{ id: 3, name: "alex", age: 22 }, | |
{ id: 4, name: "alex", age: 30 } | |
]; | |
const students2 = [ | |
{ id: 1, name: "Frank", age: 100 }, | |
{ id: 2, name: "Jay", age: 22 }, | |
{ id: 3, name: "Frank", age: 22 }, | |
{ id: 4, name: "Frank", age: 30 }, | |
{ id: 5, name: "Jay", age: 10 }, | |
{ id: 6, name: "Alex", age: 100 } | |
]; | |
const sortAdv = function(a,b) { | |
if (a.name < b.name) { | |
return -1; | |
} else if (a.name > b.name) { | |
return 1; | |
} else if (a.age > b.age) { | |
return -1; | |
} else if (a.age < b.age) { | |
return 1; | |
} else { | |
return 0; | |
} | |
}; | |
students.sort((a,b) => sortAdv(a,b)); | |
students2.sort((a,b) => sortAdv(a,b)); | |
console.log(students); | |
console.log(students2); | |
// Legacy code that works with proper syntax but can only be used once. | |
// let studentsSorted = students.sort((a, b) => { | |
// if (a.name < b.name) { | |
// return -1; | |
// } else if (a.name > b.name) { | |
// return 1; | |
// } else if (a.age > b.age) { | |
// return -1; | |
// } else if (a.age < b.age) { | |
// return 1; | |
// } else { | |
// return 0; | |
// } | |
// } | |
// ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment