Skip to content
Advertisement

How to sort prompt answer by price

I’m having a small project where I have to do a shopping list (for fruit salad) which allows user to add products and set prices for them. I’ve managed to do this so far that the “final” prompt shows all added products and prices for the user. Problem is that it should show all this from lowest to the highest by the price. I’ve tried to search information about this but haven’t found anything relevant. Is there any help for me? Thank you in advance!

JavaScript

Here you can see the edited code:

JavaScript

Advertisement

Answer

The key thing that you need to do to make this problem easier is to maintain a list of objects representing the ingredients rather than a list of interpolated strings such as “apple €1.50”. When you store objects (containing the ingredient name and the price) you now have the source data in a form that is flexible and can be used for all kinds of things, such as sorting by ingredient name, sorting by price (ascending or descending), filtering on name or price, etc.

Generally, it’s better to store and manipulate data in an elemental form and only transform that into something derived such as the description “apple €1.50” at the point you need to do that.

Here’s an example that runs outside the browser and has pre-created data:

JavaScript

In your code, to populate the items array, you could use:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement