将具有特定值的元素移动到js中排序数组的底部



我有一个对象数组,我想按特定值(例如price)对其进行排序。这些对象有一个叫做"status"的项,它可以有"available", "reserved" or "occupied"。对f.x价格的排序工作得很好,但我想要实现的是采取排序数组,并拿出具有"available"以外的状态的项目,并将它们放在数组的底部,"reserved""occupied"之前,但也按其价格排序。

那么当我有一个随机排序的数组

[{
id: 1619,
address: "Street 1",
rooms: 3,
price: 10695, 
status: "Available",
},
{
id: 1620,
address: "Street 5",
rooms: 3,
price: 7859, 
status: "Available",
},
{
id: 1626,
address: "Street 7",
rooms: 3,
price: 8595, 
status: "Reserved",
},
{
id: 1624,
address: "Street 11",
rooms: 4,
price: 9795, 
status: "Occupied",
},
{
id: 1624,
address: "Street 3",
rooms: 4,
price: 2856, 
status: "Reserved",
}]

使用和

function sortList(property, list, order) {
list.sort(function (a, b) {
if (a[property] === b[property]) {
return 0;
}
const va = a[property];
const vb = b[property];
if (order === 'asc') {
return va < vb ? 1 : -1;
}
return va > vb ? 1 : -1;
});
}
sortList("price", list, "desc");

按价格排序-这很好。然后,我想把这个排序列表放到"Reserved"one_answers";Occupied"到数组的底部-仍然按价格排序,所以我最终得到这样一个数组:

[{
id: 1620,
address: "Street 5",
rooms: 3,
price: 7859, 
status: "Available",
},
{
id: 1619,
address: "Street 1",
rooms: 3,
price: 10695, 
status: "Available",
},
{
id: 1624,
address: "Street 3",
rooms: 4,
price: 2856, 
status: "Reserved",
},
{
id: 1626,
address: "Street 7",
rooms: 3,
price: 8595, 
status: "Reserved",
},
{
id: 1624,
address: "Street 11",
rooms: 4,
price: 9795, 
status: "Occupied",
}]

过滤出您想要的项目,将它们从列表中删除,然后将它们推到列表末尾(排序后)。

const list = [{
id: 1619,
address: "Street 1",
rooms: 3,
price: 10695,
status: "Available",
},
{
id: 1620,
address: "Street 5",
rooms: 3,
price: 7859,
status: "Available",
},
{
id: 1626,
address: "Street 7",
rooms: 3,
price: 8595,
status: "Reserved",
},
{
id: 1624,
address: "Street 11",
rooms: 4,
price: 9795,
status: "Occupied",
},
{
id: 1624,
address: "Street 3",
rooms: 4,
price: 2856,
status: "Reserved",
}
];
function sortList(property, list, order) {
list.sort(function(a, b) {
if (a[property] === b[property]) {
return 0;
}
const va = a[property];
const vb = b[property];
if (order === 'asc') {
return va < vb ? 1 : -1;
}
return va > vb ? 1 : -1;
});
}
function extractItems(list) {
const extracted = list.filter(el => el.status == "Reserved" || el.status == "Occupied");

list = list.filter((el) => !extracted.includes(el));

list.push(extracted);

return list;
}
sortList("price", list, "desc");
newList = extractItems(list)
console.log(newList);

使用array的排序函数(list是你的原始数组):

const l = list.sort( (a,b) => {
if(a.status === b.status) return a.price - b.price;
const x = a.status === "Available" ? 0 : a.status === "Reserved" ? 1 : 2;
const y = b.status === "Available" ? 0 : b.status === "Reserved" ? 1 : 2;
return x-y;
});
console.log(l);

函数只比较价格,如果状态相同,否则比较状态。

相关内容

  • 没有找到相关文章