gpt4 book ai didi

javascript - 如何按数组字段值javascript对数组进行排序

转载 作者:行者123 更新时间:2023-12-03 20:16:10 24 4
gpt4 key购买 nike

我有以下数组:

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;
}

获得预期结果的正确方法是什么?

最佳答案

您可以使用localeCompare 方法。

var objs = [ { id: 'X82ns', name: 'james', presence: 'online' }, { id: '8YSHJ', name: 'mary', presence: 'offline' }, { id: '7XHSK', name: 'rene', presence: 'online' } ];

objs.sort((a,b) => b.presence.localeCompare(a.presence));
console.log(objs);

不要忘记 sort() 方法排序数组的元素就位所以你不需要使用const newArray = objs.sort....

关于javascript - 如何按数组字段值javascript对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50502929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com