How to sort an array with objects when you have more than two objects?
In the code below there are only two objects, then the conditional statement is working fine, but what happens if we add an third object?
const courses = [
{ id: 1, name: 'Node.js'},
{ id: 2, name: 'javascript.js'}
];
courses.sort(function(a, b){
//a < b => -1;
//a > b => 1;
//a === b => 0;
const nameA = a.name.toUpperCase();
const nameB = b.name.toUpperCase();
if (nameA < b.name) return -1;
if (nameB > b.name) return 1;
return 0;
});
console.log(courses);
Here is what I know:
Sorting is done on some criteria: e.g., sort by name, id, age, …
So, if you want to sort an array of objects, you will need to set the criteria first (like sort by name or id as in your example)
Then you can use
.sort(function(a, b){
let firstVal = a.propertyName;
let secondVal = b.propertyName;
// Here propertyName can be your criteria (age, value, id, name, lastName, points...)
// compare these items and return the necessary value (like, 0, 1, -1) depending upon the result.
// if ( firstVal > secondVal ) return 1;
// if ( firstVal < secondVal ) return -1;
// if ( firstVal == secondVal ) return 0;
});
So, the answer is:
you need a switch block where you can do;
switch( criteria ) {
case criteria_1:
// do something here.
break;
case criteria_2:
// do something here.
break;
case criteria_3:
// do something here.
break;
default:
// do something here.
break;
}
Can someone help me understand what is happening “under the hood” for the if statements. I don’t understand why we are returning -1, 1, and 0 or what the function is doing with these values.
courses.sort(function(a, b) {
const nameA = a.name.toUpperCase(); // this ensures that they are compared equally to sort them
const nameB = b.name.toUpperCase();
console.log(nameA);
console.log(nameB);
if (nameA < nameB) return -1; // I don't understand why we return these values. It was not explained.
if (nameA> nameB) return 1;
return 0;
});
I am grateful for any and all feedback.