什么是正确的运算符<或&&

Mal*_*own 3 javascript

我需要根据布尔属性对数组中的对象进行排序.我的代码有效,但它似乎不是正确的方法,我无法弄清楚为什么.

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)
Run Code Online (Sandbox Code Playgroud)

我应该使用大于小于运算符还是包含运算符"&&"?

(b.completed < a.completed){ // (or) !b.completed && a.completed
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)