Search code examples
javascriptlodash

lodash sorting array by discountPrice if discount is active


I'm looking for a way (preferably lodash) to sort the games by discountPrice if disountActive is true, else by price.

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

This is the result i'm looking for.

  { 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 },

Solution

  • You could use sort. Create a custom function which returns the price value based on discountActive. Then subtract the value for a and b in the comapreFunction to sort them in ascending order

    const games = [{name:'wow',price:10,discountActive:!1,discountPrice:9},{name:'doom',price:5,discountActive:!0,discountPrice:4},{name:'mk',price:15,discountActive:!1,discountPrice:11},{name:'aoe',price:20,discountActive:!0,discountPrice:10}];
     
    const value = o => o.discountActive ? o.discountPrice : o.price;
    
    games.sort((a, b) => value(a) - value(b))
    
    console.log(games)