1

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.30'},{'name':'oranges','price':'199.30'}];

When I try to sort by price, I am trying both

return food.sort((a, b) => (a.price> b.price) ? 1 : -1);
AND
return _.orderBy(food, 'price')

However it seems this interprets the price $99.30 as higher than $222.30 - I am assuming because 9 is higher than 2?

Any help would be appreciated! I am also wondering if there is a way to order largest to smallest and vice versa.

2
  • 1
    your prices are string. need to make them numeric values Commented Apr 5, 2021 at 19:49
  • Do the prices have to be in single quotes. Could be causing the issue? Commented Apr 5, 2021 at 19:51

5 Answers 5

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Quote: "That's... not how sort() works it expects 0, 1, or -1" And when it is equal?
0

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

Comments

0

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

 function compare( a, b ) {
  if ( parseFloat(a.price) < parseFloat(b.price) ){
    return -1;
  }
  if ( parseFloat(a.price) > parseFloat(b.price) ){
    return 1;
  }
  return 0;
}

food.sort( compare );

or


food.sort((a, b) => (parseFloat(a.price) > parseFloat(b.price)) ? 1 : -1);

Comments

0

The prices are stored as strings; this makes it hard. It will compare each price as strings, one character at a time, left to right.

Consider converting to floats and simplifying the code:

return food.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.