How can I sort an array so all objects with a value of true
for the key can_friend
will be first in the array?
var people = [{can_friend: true}, {can_friend: false}, {can_friend: true}]
would get sorted to
var desired_result = [{can_friend: true}, {can_friend: true}, {can_friend: false}]
答案 0 :(得分:2)
With a standard sort
using can_friend
as criterion and the fact that booleans convert to 1
and 0
on subtraction:
people.sort(function (a, b) { return b.can_friend - a.can_friend; });
答案 1 :(得分:2)
由于问题标有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 );
答案 2 :(得分:1)
Try this:
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;
});
答案 3 :(得分:0)
This is in plain JS, which works for the situation perfectly:
people.sort(function(item) {
return !item.can_friend;
});