我有以下数组:
var objs = [
{ id: 'X82ns', name: 'james', presence: 'online' },
{ id: '8YSHJ', name: 'mary', presence: 'offline' },
{ id: '7XHSK', name: 'rene', presence: 'online' }
];
我想对数组进行排序,以便通过'在线'在线'返回一个新数组。用户在离线项目之前首先显示。
因此,如果排序,它应该返回如下内容:
var objs = [
{ id: 'X82ns', name: 'james', presence: 'online' },
{ id: '7XHSK', name: 'rene', presence: 'online' },
{ id: '8YSHJ', name: 'mary', presence: 'offline' }
];
这样的事情:
const newArray = objs.sort((a, b) => {
if (a.presence === 'online') {
return 1;
} else if (b.presence === 'offline') {
return -1;
} else {
return 0;
}
})
return newArray;
}
获得预期结果的正确方法是什么?
答案 0 :(得分:1)
使用条件为 a.presence<的sort
函数b.presence 因为online
大于offline
(f
和n
)
var objs = [
{ id: 'X82ns', name: 'james', presence: 'online' },
{ id: '8YSHJ', name: 'mary', presence: 'offline' },
{ id: '7XHSK', name: 'rene', presence: 'online' }
];
objs.sort(function(a, b) {
return a.presence < b.presence;
});
console.log(objs);
答案 1 :(得分:1)
您只需将字符串与>
,=
和<
进行比较
let objs = [
{ id: 'X82ns', name: 'james', presence: 'online' },
{ id: '8YSHJ', name: 'mary', presence: 'offline' },
{ id: '7XHSK', name: 'rene', presence: 'online' }
];
let res = objs.sort((a,b) => a.presence > b.presence ? -1 : a.presence == b.presence ? 0 : 1);
console.log(res);
答案 2 :(得分:1)
您可以将具有订单的对象作为值并按其排序。这允许使用未知值的默认值。
var array = [{ id: 'X82ns', name: 'james', presence: 'online' }, { id: '8YSHJ', name: 'mary', presence: 'offline' }, { id: '7XHSK', name: 'rene', presence: 'online' }],
order = { online: 1, offline: 2, default: Infinity };
array.sort((a, b) => (order[a.presence] || order.default) - (order[b.presence] || order.default));
console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 3 :(得分:1)
使用>
符号首先获取online
,最后获得offline
。您还可以创建单独的函数sortFn
,以便可以为多个数组重用此逻辑。
var objs = [
{ id: 'X82ns', name: 'james', presence: 'online' },
{ id: '8YSHJ', name: 'mary', presence: 'offline' },
{ id: '7XHSK', name: 'rene', presence: 'online' }
];
function sortFn(a, b){
return b.presence > a.presence;
}
objs.sort(sortFn);
console.log(objs);
&#13;
答案 4 :(得分:1)
您需要实际比较这些项目,如果它们现在相同,请检查presence
var objs = [
{ id: 'X82ns', name: 'james', presence: 'online' },
{ id: '8YSHJ', name: 'mary', presence: 'offline' },
{ id: '7XHSK', name: 'rene', presence: 'online' }
];
const newArray = objs.sort((a, b) => {
if (a.presence !== b.presence) {
return a.presence === "online" ? -1 : 1;
}
return 0;
});
console.log(newArray);
&#13;
答案 5 :(得分:0)
试试这个:
var objs = [
{ id: 'X82ns', name: 'james', presence: 'online' },
{ id: '8YSHJ', name: 'mary', presence: 'offline' },
{ id: '7XHSK', name: 'rene', presence: 'online' }
];
var statusOrder = ["online", "offline"];
objs = objs.sort(function(a, b) {
return statusOrder.indexOf(a.presence) - statusOrder.indexOf(b.presence);
});
&#13;
ECMAScript6更短:
objs = objs.sort((a, b) => statusOrder.indexOf(a.presence) - statusOrder.indexOf(b.presence));
&#13;