我有一個陣列物件
const d = [
{ id: 20, text: 'deaf' },
{ id: 30, text: 'acta', },
{ id: 0, text: 'deema1' },
{ id: -1, text: 'deema2' },
]
我想按文本對陣列進行排序,但希望將 id -1 和 0 始終放在最前面,所以結果是
// sorted
[
{ id: -1, text: 'deema2' },
{ id: 0, text: 'deema1' },
{ id: 30, text: 'acta' },
{ id: 20, text: 'deaf' },
]
我試圖排序,d.sort((a, b) => (a.text).localeCompare(b.text))但不確定如何處理案例 -1 和 0
const d = [
{ id: 20, text: 'deaf' },
{ id: 30, text: 'acta', },
{ id: 0, text: 'deema1' },
{ id: -1, text: 'deema2' },
];
d.sort((a, b) => (a.text).localeCompare(b.text))
console.log(d);
uj5u.com熱心網友回復:
您可以使用indexOf:
const d = [
{ id: 20, text: 'deaf' },
{ id: 30, text: 'acta', },
{ id: 0, text: 'deema1' },
{ id: -1, text: 'deema2' },
{ id: 0, text: 'ace' },
{ id: -999, text: 'hello' },
{ id: 800, text: 'game' },
]
d.sort((a, b) => [0,-1].indexOf(b.id) - [0,-1].indexOf(a.id)
|| a.text.localeCompare(b.text));
console.log(d);
這將id首先用 -1 對所有物件進行排序,其中,該text屬性將定義順序,然后是所有物件用id0 (再次相對排序text),最后是所有其他物件text。
如果您希望 0 和 -1 之間沒有區別,而是按它們text之間進行排序,則使用includes代替indexOf:
const d = [
{ id: 20, text: 'deaf' },
{ id: 30, text: 'acta', },
{ id: 0, text: 'deema1' },
{ id: -1, text: 'deema2' },
{ id: 0, text: 'ace' },
{ id: -999, text: 'hello' },
{ id: 800, text: 'game' },
]
d.sort((a, b) => [0,-1].includes(b.id) - [0,-1].includes(a.id)
|| a.text.localeCompare(b.text));
console.log(d);
uj5u.com熱心網友回復:
從上面的答案之一稍微修改為使用管道運算子,這樣您就可以通過使用更多管道來添加您希望的任何其他數字。
const d = [
{ id: 20, text: 'deaf' },
{ id: 30, text: 'acta', },
{ id: 0, text: 'deema1' },
{ id: -1, text: 'deema2' },
{ id: 0, text: 'ace' },
{ id: -999, text: 'hello' },
{ id: 800, text: 'game' },
]
const sorted = d.sort((a, b) => {
if (a.id === -1 || a.id === 0) {
return -1;
}
return a.text.localeCompare(b.text);
});
console.log(sorted)
uj5u.com熱心網友回復:
您可以在其中放置多個條件sort以獲得所需的結果。第一個條件比下一個更重要,依此類推。這就是它的樣子:
const d = [{
id: 20,
text: 'deaf'
},
{
id: 30,
text: 'acta',
},
{
id: 0,
text: 'deema1'
},
{
id: -1,
text: 'deema2'
},
]
const sorted = d.sort((a, b) => {
if (a.id === -1) {
return -1;
}
if (a.id === 0) {
return -1;
}
return a.text.localeCompare(b.text);
});
console.log(sorted)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492024.html
標籤:javascript 算法
