I was following a course and when i reached the challenge section the teacher asked to write down a code that sorts this objects array which contains some 'todos' with the properties: 'text, and completed (boolean)' and the sorting should work like this: the uncompleted todos (false) should be first and the the completed one should be the last. i wrote down a code and it actually worked and sorted the array as requested but when i saw how the instructor solved this challenge I was a bit confused because he used a different way so i wanted to ask the internet about which one (my code or the instructor's) is the best and more accurate. I'm actually confused because my code worked however I gave sort() function only one argument, or parameter (a) and it sorted the array as i wanted, so please i need an explanation
This is the basic objects-array:
// The basic objects array:
const todos = [{
text: 'wake up',
completed: true
}, {
text: 'get some food',
completed: false
}, {
text: 'play csgo',
completed: false
}, {
text: 'play minecraft',
completed: true
}, {
text: 'learn javascript',
completed: false
}];
This is the code i wrote:
// My code
let sortTodos = function(todos) {
todos.sort(function(a) {
if (a.completed === false) {
return -1;
}
else if (a.completed === true){
return 1;
}
else {
return 0;
}
})
}
sortTodos(todos);
console.log(todos);
the instructor's code
// The instructor's code
const sortTodos = function (todos) {
todos.sort(function (a, b) {
if (!a.completed && b.completed) {
return -1
} else if (!b.completed && a.completed) {
return 1
} else {
return 0
}
})
}
the output is :
[ { text: 'get some food', completed: false },
{ text: 'play csgo', completed: false },
{ text: 'learn javascript', completed: false },
{ text: 'play minecraft', completed: true },
{ text: 'wake up', completed: true } ]