I am doing exercises por the Ultimate JavaScrip course Part 1 - Fundamentals, in Section 6- Arrays, Lesson 12- Sorting Arrays. Please tell me why, when I comment the statements that use the courses.sort(function(a, b)… the array courses appear unsorted, but when I un-comment them, the arrays (logged to console at different times ) appear all sorted :
Please run this code as is, and look at the console. Then un-comment the last part that use the “sort(function)” and run it again and you will see. Here is the code:
// When sorting arrays with objects, there is extra work to do:
const courses = [
{ id:3, name: ‘Node.js’},
{ id:1, name: ‘JavaScript’},
{ id:2, name: ‘HTML5’},
{ id:4, name: ‘CSS3’} // we want to sort based in the name
];
console.log('Original: ', courses);
courses.sort();
console.log('with sort: ', courses); // Nothig happens, so…
// courses.sort(function(a, b) {
// // a < b => -1
// // a > b => 1
// // a === b => 0;
// // toUpperCase or toLowerCase to avoid missorting by lower/upper casing
// const nameA = a.name.toUpperCase(); // if toLowerCase be sure are in both
// const nameB = b.name.toUpperCase();
// if (nameA < nameB) return -1;
// if (nameA > nameB) return 1;
// return 0;
// });
// console.log('with function: ', courses);
//////// I don´t know why, but executing the sort(function),
//////// courses appear sorted from the beggining!!!