0

I'm trying to sort objects based by its property (price)

var arr = [{
        name: 'Apple',
        price: '1.03'
    },
    {
        name: 'Cherry',
        price: '0.33'
    },
    {
        name: 'Mango',
        price: '0.53'
    }
]

Now i use lodash to sort it by its price:

arr = _.sortBy(arr, 'price' ).reverse();

Now arr[0] should be Apple, since it's price is highest, but it's not. What could be wrong?

4 Answers4

1

As everyone is mentioning you are sorting Strings so your outcome is not what you are expecting. To sort based on price use the following (or similar):

var arr = [{
        name: 'Apple',
        price: '1.03'
    },
    {
        name: 'Cherry',
        price: '0.33'
    },
    {
        name: 'Mango',
        price: '0.53'
    }
]

arr.sort(function(a, b){
 return parseFloat(b.price) - parseFloat(a.price);
});

console.log(arr);
Matt
  • 1,062
  • 1
  • 8
  • 11
0

Since there isn't an answer using Lodash here, I am going to provide one in case someone else stumbles across this question in the future:

// Your code:
var arr = [{
        name: 'Apple',
        price: '1.03'
    },
    {
        name: 'Cherry',
        price: '0.33'
    },
    {
        name: 'Mango',
        price: '0.53'
    }
]

// Yours that isn't working:
// arr = _.sortBy(arr, 'price' ).reverse();

const sortedArr = _.chain(arr)
  .map((val) => _.toNumber(val.price))
  .sortBy()
  .value();
  
console.log(sortedArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30
0

Since the price value inside each object is a string, you are getting a different result. You can take advantage of function callback and convert your price value to a number and the use sortBy to sort your data based on the numeric value of price.

var arr = [{name: 'Apple',price: '1.03'},{name: 'Cherry',price: '0.33'},{name: 'Mango',price: '0.53'}];
_.sortBy(arr, ({price}) => +price);
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

If you are using LoDash, this is how i did it:

var arr = [{name: 'Apple',price: '1.03',weight:'12'},{name: 'Cherry',price: '0.33', 
weight:'12',weight:'12'},{name: 'Mango',price: '0.53',weight:'12'}];

SortyBy(sortName, SortType, order)
{

  if(SortType == 1)
  {
       _.orderBy(arr,[function(o) { return parseFloat(o[sortName]); }],order);
  }
  else
  {
      _.orderBy(arr,[function(o) { return o[sortName]; }], order);
  }
}

//you would then call:
SortBy("price",1, "asc");
SortBy("weight",1, "asc");
SortBy("name",0,"desc");`
Sam R.
  • 1