我需要根据布尔属性对数组内的对象进行排序。我的代码有效,但似乎不是正确的方法,我不知道为什么。
const todos = [{
text: 'Check emails for the day',
completed: true
},{
text: 'Walk the dog',
completed: true
},{
text: 'Go to the store for groceries',
completed: false
},{
text: 'Pick up kids from school',
completed: false
},{
text: 'Do online classes',
completed: false
}]
const sortTodos = function (todos) {
todos.sort(function (a,b) {
if (a.completed < b.completed) { // (or) a.completed === false && b.completed === true
return -1
} else if (b.completed < a.completed){ // (or) !b.completed && a.completed
return 1
} else {
return 0
}
})
}
sortTodos(todos)
console.log(todos)
我应该使用大于小于运算符还是包含运算符“ &&”?
(b.completed < a.completed){ // (or) !b.completed && a.completed
答案 0 :(得分:5)
您可以采用布尔值的差值。减法会将值强制转换为数字。
const
todos = [{ text: 'Check emails for the day', completed: true }, { text: 'Walk the dog', completed: true }, { text: 'Go to the store for groceries', completed: false }, { text: 'Pick up kids from school', completed: false }, { text: 'Do online classes', completed: false }],
sortTodos = todos => todos.sort((a, b) => a.completed - b.completed);
sortTodos(todos);
console.log(todos);
.as-console-wrapper { max-height: 100% !important; top: 0; }