2009-06-11 03:59:54 8 Comments
I've got the following objects using AJAX and stored them in an array:
var homes = [
{
"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"
}
];
How do I create a function to sort the objects by the price
property in ascending or descending order using JavaScript only?
Related Questions
Sponsored Content
34 Answered Questions
[SOLVED] For-each over an array in JavaScript?
- 2012-02-17 13:51:48
- Dante1986
- 3924956 View
- 4462 Score
- 34 Answer
- Tags: javascript arrays loops foreach iteration
89 Answered Questions
[SOLVED] How do I remove a particular element from an array in JavaScript?
- 2011-04-23 22:17:18
- Walker
- 6168792 View
- 7694 Score
- 89 Answer
- Tags: javascript arrays
41 Answered Questions
[SOLVED] Loop through an array in JavaScript
- 2010-06-10 00:04:27
- Mark Szymanski
- 3544244 View
- 2960 Score
- 41 Answer
- Tags: javascript arrays loops for-loop
34 Answered Questions
[SOLVED] How do I sort a dictionary by value?
- 2009-03-05 00:49:05
- Gern Blanston
- 2514138 View
- 3424 Score
- 34 Answer
- Tags: python sorting dictionary
41 Answered Questions
[SOLVED] How do I remove a property from a JavaScript object?
- 2008-10-16 10:57:45
- johnstok
- 2090817 View
- 5839 Score
- 41 Answer
- Tags: javascript javascript-objects object-properties
43 Answered Questions
[SOLVED] Sort array of objects by string property value
- 2009-07-15 03:17:47
- Tyrone Slothrop
- 1375113 View
- 2552 Score
- 43 Answer
- Tags: javascript arrays sorting
47 Answered Questions
[SOLVED] How to check if an object is an array?
- 2011-01-23 18:53:04
- mpen
- 1448388 View
- 2588 Score
- 47 Answer
- Tags: javascript arrays javascript-objects
47 Answered Questions
[SOLVED] How do I check if an array includes a value in JavaScript?
- 2008-10-25 22:14:40
- brad
- 2419767 View
- 3798 Score
- 47 Answer
- Tags: javascript arrays algorithm time-complexity javascript-objects
42 Answered Questions
[SOLVED] Detecting an undefined object property
- 2008-08-26 07:25:08
- Matt Sheppard
- 1125032 View
- 2753 Score
- 42 Answer
- Tags: javascript object undefined
30 Answered Questions
[SOLVED] How to append something to an array?
- 2008-12-09 00:20:05
- interstar
- 3019778 View
- 2895 Score
- 30 Answer
- Tags: javascript arrays append
28 comments
@Ishan Liyanage 2013-11-14 05:55:48
for string sorting in case some one needs it,
@Triptych 2009-06-11 04:33:59
Here's a more flexible version, which allows you to create reusable sort functions, and sort by any field.
@nickb 2011-10-31 05:47:08
Even though this is super cool, isn't it terribly inefficient. The speed would be O(n*n). Any way to use a more efficient sort algorithm, like Quick Sort while also keeping it extensible like your answer above?
@Triptych 2011-10-31 07:04:09
nickb - you're misreading the code.
sort_by
runs in O(1), and returns a function used by the built-in sort (O(N log N)) to compare items in a list. The total complexity is O(n log n) * O(1) which reduces to O(n log n), or the same as a quick sort.@Abby 2012-04-26 13:42:40
One issue I have with this is that with reverse=false, it will sort numbers as 1,2,3,4... but Strings as z,y,x...
@ErikE 2012-08-07 01:18:00
A small enhancement:
var key = primer ? function (x) { return primer(x[field]); } : function (x) { return x[field]; }
@EleventyOne 2013-08-29 20:06:29
Note that the
!!reverse
makes the results descending by default (as thejsfiddle
code above highlights as well. If you want ascending by default, just make it!reverse
.@Ingo Bürk 2013-12-03 21:28:52
While
[1,-1][+!!reverse]
looks cool, it's a horrible thing to do. If a user can't call your method properly, punish him, not try to somehow make sense of it, no matter what.@Gerrit Brink 2015-03-05 14:14:08
Wouldn't it be better to prepare the source data, this would cause consecutive parsing when clearly the source data needs some tweaking.
@MatFiz 2016-08-26 08:27:08
I found it quite usefull to add to to
Object
prototype, so you can easily use it at any object:javascript Object.prototype.sort_by = function(field,reverse,primer) { var sort_by = function(field, reverse, primer){ var key = primer ? function(x) {return primer(x[field])} : function(x) {return x[field]}; reverse = !reverse ? 1 : -1; return function (a, b) { return a = key(a), b = key(b), reverse * ((a > b) - (b > a)); } } return this.sort(sort_by(field,reverse,primer)) }
@Santosh 2019-01-24 12:26:53
I'm little late for the party but below is my logic for sorting.
@rashedcs 2019-07-30 03:40:19
A simple code :
@Arushi Bajpai 2019-06-14 08:18:37
Descending order of price:
Ascending order of price:
@Andrew Rayan 2019-03-10 14:45:20
Create a function and sort based on the input using below code
@Mitchell Skurnik 2018-06-01 23:44:39
While I am aware that the OP wanted to sort an array of numbers, this question has been marked as the answer for similar questions regarding strings. To that fact, the above answers do not consider sorting an array of text where casing is important. Most answers take the string values and convert them to uppercase/lowercase and then sort one way or another. The requirements that I adhere to are simple:
What I expect is
[ A, a, B, b, C, c ]
but the answers above returnA, B, C, a, b, c
. I actually scratched my head on this for longer than I wanted (which is why I am posting this in hopes that it will help at least one other person). While two users mention thelocaleCompare
function in the comments for the marked answer, I didn't see that until after I stumbled upon the function while searching around. After reading the String.prototype.localeCompare() documentation I was able to come up with this:This tells the function to sort uppercase values before lowercase values. The second parameter in the
localeCompare
function is to define the locale but if you leave it asundefined
it automatically figures out the locale for you.This works the same for sorting an array of objects as well:
@Stephen Quan 2016-11-25 01:02:06
If you have an ES6 compliant browser you can use:
The difference between ascending and descending sort order is the sign of the value returned by your compare function:
Here's a working code snippet:
@jherax 2014-11-05 16:28:36
I recommend GitHub: Array sortBy - a best implementation of
sortBy
method which uses the Schwartzian transformBut for now we are going to try this approach Gist: sortBy-old.js.
Let's create a method to sort arrays being able to arrange objects by some property.
Creating the sorting function
Setting unsorted data
Using it
Arrange the array, by
"date"
asString
If you want to ignore case sensitive, set the
parser
callback:If you want to convert the
"date"
field asDate
type:Here you can play with the code: jsbin.com/lesebi
Thanks to @Ozesh by his feedback, the issue related to properties with falsy values was fixed.
@TSNev 2016-08-25 13:51:11
This seems to breaks when a field is null.
@Ozesh 2016-10-20 04:29:49
In case you are sorting through numbers and you encounter a '0' in between the array of objects, you might notice that the above code breaks.. Here is a quick fix for that :
var checkNaN = function (value) { return Number.isNaN(Number(value)) ? 0 : value; }
followed by: return function (array, o) { .... a = _getItem.call(o, a); a = checkNaN(a); b = _getItem.call(o, b); b = checkNaN(b); return o.desc * (a < b ? -1 : +(a > b)); });@Stobor 2009-06-11 04:12:35
Sort homes by price in ascending order:
Or after ES6 version:
Some documentation can be found here.
@bradvido 2014-05-27 13:51:53
You can use
string1.localeCompare(string2)
for string comparison@Don Kirkby 2015-05-01 21:58:58
Keep in mind that
localeCompare()
is case insensitive. If you want case sensitive, you can use(string1 > string2) - (string1 < string2)
. The boolean values are coerced to integer 0 and 1 to calculate the difference.@vjy tiwari 2017-07-25 17:42:58
What about alphanumeric strings comparison e.g. Ajay123Kumar , Kapil4Kumar562 etc ?
@Pointy 2017-08-27 12:41:18
@DonKirkby I know that's an old comment, but
localeCompare()
is not case insensitive in all locales; in US English in every browser I've experienced, it's consistently case-sensitive.@Don Kirkby 2017-08-28 16:11:04
Thanks for the update, @Pointy, I don't remember running into this problem, but perhaps the behaviour has changed in the last couple of years. Regardless, the
localeCompare()
documentation shows that you can explicitly state whether you want case sensitivity, numeric sorting, and other options.@Nina Scholz 2018-01-12 11:18:03
parseFloat
is uperfluous, because-
operator converts every operands into number.@user1063287 2018-05-20 05:45:19
can anyone please confirm if this is correct fleshed out example of @bradvido 's answer?
[{"name": "adam", id:0},{"name": "craig", id:1},{"name": "bruce", id:2}].sort(function(a, b) {return a.name.localeCompare(b.name)});
@sg28 2018-07-26 07:19:33
Good ,thanks ,but as mentioned in the MDN sort function is not reliable
@Stobor 2018-07-30 01:42:22
@sg28 I think you've misunderstood the MDN explanation. It does not say that the sort function is not reliable, it says that it is not stable. I understand why this can be confusing, but that is not a claim that it is not suitable for use. In the context of sorting algorithms, the term stable has a specific meaning - that "equal" elements in the list are sorted in the same order as in the input. This is completely unrelated to the idea of code which is unstable (i.e. not yet ready for use).
@Jorge Valvert 2018-10-30 04:13:35
If you want to sort by a specific string values for example by city you could use: this.homes.sort((current,next)=>{ return current.city.localeCompare(next.city)});
@OzzyCzech 2018-03-07 07:13:45
You will need two function
Then you can apply this to any object property:
@Umesh 2018-02-07 11:08:26
For a normal array of elements values only:
For an array of objects:
@Ajay Singh 2017-08-06 17:53:28
This could have been achieved through a simple one line valueof() sort function. Run code snippet below to see demo.
@Pradip Talaviya 2017-04-26 13:13:06
For sort on multiple array object field. Enter your field name in
arrprop
array like["a","b","c"]
then pass in second parameterarrsource
actual source we want to sort.@mythicalcoder 2017-02-07 21:39:53
Here is a slightly modified version of elegant implementation from the book "JavaScript: The Good Parts".
NOTE: This version of
by
is stable. It preserves the order of the first sort while performing the next chained sort.I have added
isAscending
parameter to it. Also converted it toES6
standards and "newer" good parts as recommended by the author.You can sort ascending as well as descending and chain sort by multiple properties.
@Vishal Kumar Sahu 2017-08-14 08:29:35
could we sort
{"first":"Curly","last":"Howard", "property" : {"id" : "1"}}
type of array by id?@mythicalcoder 2017-08-15 21:29:19
yes, the function has to be slightly modified to take in a new parameter, say, nestedName. You then call
by
with name="property", nestedName="id"@CracyD 2016-07-26 08:43:31
With ECMAScript 6 StoBor's answer can be done even more concise:
@Evan Carroll 2016-05-25 14:53:17
Use lodash.sortBy, (instructions using commonjs, you can also just put the script include-tag for the cdn at the top of your html)
Descending order
Ascending order
@mpen 2016-10-17 01:13:49
Or
const sortBy = require('lodash/sortBy'); let calendars = sortBy(calendarListResponse.items, cal => cal.summary);
@montelof 2016-12-08 21:56:34
not sure if loadash changed recently by now its named OrderBy
import { orderBy } from 'lodash'; ... ... return orderBy ( rows, 'fieldName' ).reverse();
@George Vrynios 2016-04-02 21:52:28
Hi after reading this article, I made a sortComparator for my needs, with the functionality to compare more than one json attributes, and i want to share it with you.
This solution compares only strings in ascending order, but the solution can be easy extended for each attribute to support: reverse ordering, other data types, to use locale, casting etc
and the result is
and another sort
with result
@Eneko Alonso 2015-09-25 02:37:47
While it is a bit of an overkill for just sorting a single array, this prototype function allows to sort Javascript arrays by any key, in ascending or descending order, including nested keys, using
dot
syntax.Usage:
Sorting by nested properties with dot-syntax or array-syntax:
Sorting by multiple keys:
You can fork the repo: https://github.com/eneko/Array.sortBy
@Tim Gilbert 2009-06-11 04:14:48
You want to sort it in Javascript, right? What you want is the
sort()
function. In this case you need to write a comparator function and pass it tosort()
, so something like this:Your comparator takes one of each of the nested hashes inside the array and decides which one is higher by checking the "price" field.
@Ricardo Marimon 2009-06-11 04:11:08
To sort it you need to create a comparator function taking two arguments. Then call the sort function with that comparator function as follows:
If you want to sort ascending switch the expressions on each side of the minus sign.
@Roland Illig 2014-05-25 20:30:34
And here's a reference that actually explains the topic instead of saying "it's too complicated, you won't understand it anyway": developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@Vitalii Fedorenko 2015-05-06 01:41:02
If you use Underscore.js, try sortBy:
@user3346960 2015-01-31 01:55:10
@Brad Bird 2014-10-30 10:28:23
I recently wrote a universal function to manage this for you if you want to use it.
@Rodolfo Jorge Nemer Nogueira 2014-09-02 13:44:37
I also worked with some kind of rating and multiple fields sort:
Result
@bob 2014-01-28 07:15:05
Here is a culmination of all answers above.
Fiddle validation: http://jsfiddle.net/bobberino/4qqk3/
@TechTurtle 2017-09-28 16:59:11
can you please explain what is the significance of having * (rev ? -1 : 1);
@bob 2017-09-29 18:16:52
That's to reverse the order (ascending vs descending) the rev portion just flips normal results when the rev argument is true. Otherwise it'll just multiple by 1 which does nothing, when set, it'll multiply the result by -1, thereby inverting the result.
@Lalit Kumar Maurya 2013-12-06 10:10:44
For sorting a array you must define a comparator function. This function always be different on your desired sorting pattern or order(i.e. ascending or descending).
Let create some functions that sort an array ascending or descending and that contains object or string or numeric values.
Sort numbers (alphabetically and ascending):
Sort numbers (alphabetically and descending):
Sort numbers (numerically and ascending):
Sort numbers (numerically and descending):
As above use sorterPriceAsc and sorterPriceDes method with your array with desired key.
@John G 2009-06-11 04:14:53
You can use the JavaScript
sort
method with a callback function: