首先对具有真值的数组进行排序

sort array with true values first

如何对数组进行排序,使键 can_friend 的值为 true 的所有对象在数组中排在第一位?

var people = [{can_friend: true}, {can_friend: false}, {can_friend: true}]

将被排序为

var desired_result = [{can_friend: true}, {can_friend: true}, {can_friend: false}]

试试这个:

people.sort(function(val1, val2) {
  if (val1.can_friend && !val2.can_friend) return -1;
  else if (!val1.can_friend && val2.can_friend) return 1;
  else return 0;
});

标准 sort 使用 can_friend 作为标准,布尔值在减法时转换为 10

people.sort(function (a, b) { return b.can_friend - a.can_friend; });

这是纯 JS,非常适合这种情况:

people.sort(function(item) {
  return !item.can_friend;
});

由于问题被标记为 underscore.js,这里有一个使用它的解决方案:

var sorted = _.sortBy( people, function(element){ return element.can_friend ? 0 : 1; } );

或更短:

var sorted = _.sortBy( people, function(e){ return !e.can_friend; } );

或使用 ES6 箭头函数语法:

var sorted = _.sortBy( people, e=>!e.can_friend );