Javascript 如果折扣处于活动状态,则按折扣价格排序lodash数组
我正在寻找一种方法,最好是lodash,如果Disonictive是真的,则按折扣价格对游戏进行排序,否则按价格排序Javascript 如果折扣处于活动状态,则按折扣价格排序lodash数组,javascript,lodash,Javascript,Lodash,我正在寻找一种方法,最好是lodash,如果Disonictive是真的,则按折扣价格对游戏进行排序,否则按价格排序 const { sortBy } = require('lodash'); const games = [ { name: 'wow', price: 10, discountActive: false, discountPrice: 9 }, { name: 'doom', price: 5, discountActive: true, discoutPrice: 4
const { sortBy } = require('lodash');
const games = [
{ name: 'wow', price: 10, discountActive: false, discountPrice: 9 },
{ name: 'doom', price: 5, discountActive: true, discoutPrice: 4 },
{ name: 'mk', price: 15, discountActive: false, discountPrice: 11 },
{ name: 'aoe', price: 20, discountActive: true, discountPrice: 10 },
];
const sorted = sortBy(games, [function (game) {
if (game.discountActive) {
return game.discountPrice;
} else {
return game.price;
}
}]);
这就是我想要的结果
{ name: 'doom', price: 5, discountActive: true, discoutPrice: 4 },
{ name: 'wow', price: 10, discountActive: false, discountPrice: 9 },
{ name: 'aoe', price: 20, discountActive: true, discountPrice: 10 },
{ name: 'mk', price: 15, discountActive: false, discountPrice: 11 },
你可以使用排序。创建一个自定义函数,该函数根据折扣返回价格值。然后减去ComaPref函数中a和b的值,以升序对它们进行排序
const games=[{name:'wow',price:10,折扣价:!1,折扣价:9},{name:'doom',price:5,折扣价:!0,折扣价:4},{name:'mk',price:15,折扣价:!1,折扣价:11},{name:'aoe',price:20,折扣价:!0,折扣价:10}];
const value=o=>o.discountActive?o、 折扣价格:o.价格;
games.sorta,b=>valuea-valueb
控制台,LogGames你的代码不是你想要的吗?我不明白你为什么要这么做?根据数组的当前格式,您可以按折扣价格或价格对其进行排序。如果仍然要排序,我建议将数组分成两个,一个使用discountActive:true,另一个使用discountActive:false,然后进行相应的排序。@riazosama lodash可以处理它,那么为什么不使用呢?