我想在JavaScript中使用两个属性布尔值和Int值对对象数组进行排序。我想要像这样输出:
{ first_nom: 'sumeet', last_nom: 'Prentice' ,offerApplicable: 'TRUE' ,price: 40},
4:55 PM { first_nom: 'Pirate', last_nom: 'Prentice' ,offerApplicable: 'TRUE' ,price: 50},
4:55 PM { first_nom: 'Lazslo', last_nom: 'Jamf' ,offerApplicable: 'TRUE' ,price: 60 },
4:55 PM { first_nom: 'jitendra', last_nom: 'Prentice' ,offerApplicable: 'TRUE' ,price: 101}
具有真值的所有对象首先也按价格排序,然后所有具有布尔值的对象为false。我能够按布尔值对它们进行排序,但我也希望按价格对它们进行排序。
我试过这个
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' ,offerApplicable: 'TRUE' ,price: 60 },
{ first_nom: 'Pig', last_nom: 'Bodine' , offerApplicable: 'FALSE' ,price: 100},
{ first_nom: 'Pirate', last_nom: 'Prentice' ,offerApplicable: 'TRUE' ,price: 50},
{ first_nom: 'nithesh', last_nom: 'Bodine' , offerApplicable: 'FALSE' ,price: 40},
{ first_nom: 'sumeet', last_nom: 'Prentice' ,offerApplicable: 'TRUE' ,price: 40},
{ first_nom: 'mahesh', last_nom: 'Bodine' , offerApplicable: 'FALSE' ,price: 40},
{ first_nom: 'jitendra', last_nom: 'Prentice' ,offerApplicable: 'TRUE' ,price: 101}
];
function compare(a,b) {
var aConcat = a["offerApplicable"] + a["price"];
var bConcat = b["offerApplicable"] + b["price"];
if (aConcat < bConcat )
return 1;
if (aConcat > bConcat )
return -1;
return 0;
}`enter code here`
console.log(objs.sort(compare));
请提前帮助谢谢。
答案 0 :(得分:0)
尝试这个比较功能
function compare(a,b) {
if (a.offerApplicable == b.offerApplicable)
return (a.price > b.price)
else return (a.offerApplicable < b.offerApplicable)
}
答案 1 :(得分:0)
您需要做的是三次检查:
$ npm -v
5.0.3
$ node -v
v6.11.0
然后返回(a.offerApplicable == 'FALSE' && b.offerApplicable ==
'TRUE')
。1
是否返回(a.offerApplicable == b.offerApplicable == 'TRUE')
。a.price > b.price
然后返回(a.offerApplicable == b.offerApplicable)
。这应该是你的代码:
a.price > b.price
<强>演示:强>
objs.sort(function compare(a,b) {
if (a.offerApplicable == 'FALSE' && b.offerApplicable == 'TRUE')
return 1;
else if(a.offerApplicable == b.offerApplicable == 'TRUE')
return a.price > b.price
else if(a.offerApplicable == b.offerApplicable)
return a.price > b.price
});
这将var objs = [{
first_nom: 'Lazslo',
last_nom: 'Jamf',
offerApplicable: 'TRUE',
price: 60
},
{
first_nom: 'Pig',
last_nom: 'Bodine',
offerApplicable: 'FALSE',
price: 100
},
{
first_nom: 'Pirate',
last_nom: 'Prentice',
offerApplicable: 'TRUE',
price: 50
},
{
first_nom: 'nithesh',
last_nom: 'Bodine',
offerApplicable: 'FALSE',
price: 40
},
{
first_nom: 'sumeet',
last_nom: 'Prentice',
offerApplicable: 'TRUE',
price: 40
},
{
first_nom: 'mahesh',
last_nom: 'Bodine',
offerApplicable: 'FALSE',
price: 40
},
{
first_nom: 'jitendra',
last_nom: 'Prentice',
offerApplicable: 'TRUE',
price: 101
}
];
console.log(objs.sort(function compare(a,b) {
if (a.offerApplicable == 'FALSE' && b.offerApplicable == 'TRUE')
return 1;
else if(a.offerApplicable == b.offerApplicable == 'TRUE')
return a.price > b.price
else if(a.offerApplicable == b.offerApplicable)
return a.price > b.price
}));
然后offerApplicable
排序。