Js Order Array Of Objects By Object Property (dollars)
I am having a heck of a time figuring this one out. I have an array of objects in my vuejs app like so: var food= [{'name':'apples','price':'222.30'},{'name':'bananas','price':'99.
Solution 1:
You have to convert the price to a number and use in your sort callback
return food.sort((a, b) =>parseFloat(a.price) - parseFloat(b.price));
Solution 2:
The problem with your code, is the values are strings.
A simple fix:
return food.sort((a, b) => (parseFloat(a.price) > parseFloat(b.price)) ? 1 : -1);
Solution 3:
Just use Number
var food= [{'name':'apples','price':'222.30'},{'name':'bananas','price':'99.30'},{'name':'oranges','price':'199.30'}];
food.sort((a, b) => (Number(a.price) > Number(b.price)) ? 1 : -1);
console.log(food);
Solution 4:
Your sort is not working as aspected because you comparing price as string
var food= [{'name':'apples','price':'222.30'},{'name':'bananas','price':'99.30'},{'name':'oranges','price':'199.30'}];
functioncompare( a, b ) {
if ( parseFloat(a.price) < parseFloat(b.price) ){
return -1;
}
if ( parseFloat(a.price) > parseFloat(b.price) ){
return1;
}
return0;
}
food.sort( compare );
or
food.sort((a, b) => (parseFloat(a.price) > parseFloat(b.price)) ? 1 : -1);
Solution 5:
The prices are stored as string
s; this makes it hard. It will compare each price as strings, one character at a time, left to right.
Consider converting to float
s and simplifying the code:
return food.sort((a, b) =>parseFloat(a.price) - parseFloat(b.price));
Post a Comment for "Js Order Array Of Objects By Object Property (dollars)"