
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting an array by price in JavaScript
Suppose we have an array of objects that contains data about some houses and price like this −
const arr = [ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { "h_id": "4", "city": "Bevery Hills", "state": "CA", "zip": "90210", "price": "319250" }, { "h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ];
We are required to write a JavaScript function that takes in one such array. The function should sort the array (either in ascending or in descending) order according to the price property of the objects (which currently is a string).
Example
The code for this will be −
const arr = [ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { "h_id": "4", "city": "Bevery Hills", "state": "CA", "zip": "90210", "price": "319250" }, { "h_id": "5", "city": "New York", "state": "NY", "zip": "00010", "price": "962500" } ]; const eitherSort = (arr = []) => { const sorter = (a, b) => { return +a.price - +b.price; }; arr.sort(sorter); }; eitherSort(arr); console.log(arr);
Output
And the output in the console will be −
[ { h_id: '3', city: 'Dallas', state: 'TX', zip: '75201', price: '162500' }, { h_id: '4', city: 'Bevery Hills', state: 'CA', zip: '90210', price: '319250' }, { h_id: '5', city: 'New York', state: 'NY', zip: '00010', price: '962500' } ]
- Related Questions & Answers
- Sorting an array by date in JavaScript
- Sorting an array of objects by an array JavaScript
- JavaScript array sorting by level
- Sorting an array of objects by property values - JavaScript
- Sorting an array object by property having falsy value - JavaScript
- Sorting an array objects by property having null value in JavaScript
- Alternative sorting of an array in JavaScript
- Sorting JavaScript object by length of array properties.
- Sorting array of Number by increasing frequency JavaScript
- Sorting an array of binary values - JavaScript
- Sorting an associative array in ascending order - JavaScript
- Sorting an array that contains undefined in JavaScript?
- Sorting only a part of an array JavaScript
- Sorting Array Elements in Javascript
- Sorting or Arranging an Array with standard array values - JavaScript
Advertisements