You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.

var data = [{ 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: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];

data.sort(function (a, b) {
    return a.city.localeCompare(b.city) || b.price - a.price;
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Or, using es6, simply:

data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
Answer from Nina Scholz on Stack Overflow
🌐
Reddit
reddit.com › r/learnjavascript › how to sort an array of objects by 3 properties?
r/learnjavascript on Reddit: How to sort an array of objects by 3 properties?
January 31, 2017 -

Fiddle: https://jsfiddle.net/seL5ysk9/2/

EDIT: In case anyone wants to attempt the full codewars exercise that spawned this question: https://www.codewars.com/kata/strings-mix/train/javascript

I have an array:

var merged = [ 
  { letter: 'e', count: 2, string: 1 },
  { letter: 'l', count: 2, string: 1 },
  { letter: 'o', count: 2, string: 1 },
  { letter: 'a', count: 1, string: 0 },
  { letter: 'd', count: 1, string: 1 },
  { letter: 'f', count: 1, string: 1 },
  { letter: 'g', count: 1, string: 2 },
  { letter: 'h', count: 1, string: 1 },
  { letter: 'k', count: 1, string: 2 },
  { letter: 'm', count: 1, string: 2 },
  { letter: 'n', count: 1, string: 1 },
  { letter: 'r', count: 1, string: 1 },
  { letter: 's', count: 1, string: 1 },
  { letter: 't', count: 1, string: 0 },
  { letter: 'u', count: 1, string: 2 } 
];

And I want it to be sorted to look like this:

[
  { letter: 'e', count: 2, string: 1 }, <== preserve ordering by count
  { letter: 'l', count: 2, string: 1 },
  { letter: 'o', count: 2, string: 1 },
  { letter: 'd', count: 1, string: 1 }, <== non-string 0: preserve alphabetical order within count #
  { letter: 'f', count: 1, string: 1 },
  { letter: 'g', count: 1, string: 2 },
  { letter: 'h', count: 1, string: 1 },
  { letter: 'k', count: 1, string: 2 },
  { letter: 'm', count: 1, string: 2 },
  { letter: 'n', count: 1, string: 1 },
  { letter: 'r', count: 1, string: 1 },
  { letter: 's', count: 1, string: 1 },
  { letter: 'u', count: 1, string: 2 },
  { letter: 'a', count: 1, string: 0 }, <== the string 0's are at the end
  { letter: 't', count: 1, string: 0 }, <== start alphabetical order again within string 0 
];

How do i make the 'string' 0 items come last within a group of equal 'counts' and then alphabetize those 'string' 0 items just within the string 0 items?

So basically it's organized first by count in descending order, then within count subgroups it's ordered alphabetically. I just don't know how to go to the next level and within each count number, group the string 0's at the end and put those in alphabetical order.

This was actually out of order first and I did a custom sort comparator function to organize by count then letter. Now I'm trying to run a second sort function just to target the string 0 items, but I don't know how--this is how far I got, which doesn't work:

merged.sort(function(a,b) {
    
    if (a.count == b.count) {
      if (a.string == 0 && b.string == 0) {
        if (a.letter < b.letter) {
            return -1;
        } else if (a.letter > b.letter) {
            return 1;   
        }
      }
    }
  
});
Top answer
1 of 4
1
You're only handling the letter cases in your comparison function. You also need to handle string and counts (when not equal). Right now its returning the implicit undefined
2 of 4
1
I think in this case you're thinking too deep. The solution is simpler than you may think. When calling Array.prototype.sort(), the provided compareFunction argument is a function that takes two arguments: namely two elements in the array to sort. All that is requested of this compareFunction, is that it returns an indication of which of these two elements has sorting priority over the other. In other words, which element comes before the other? You don't have to do anything more than that. Listing your criteria for sorting the elements, we get this: The element with the highest count comes first. For equal counts, the element with the lowest letter comes first. Elements with a string of 0 come last. But there's something slightly wrong with this list. You see, the priorities are off. Your highest priority sorting rule here, is the last one. If you apply only this rule directly to the sorted result you're looking for, it will remain mostly unchanged - all the 0 string elements come last, the rest come before them. Do this for any of the other two rules, and the result set is entirely scrambled. Your first sorting criterium is second in priority, and the second criterium is third in priority. Now, I'll apply these sorting rules, in correct order of priority, into a compareFunction, translating them as directly as possible: merged.sort(function (a, b) { let stringDiff = b.string - a.string; if (stringDiff < 0 && b.string === 0) return -1; else if (stringDiff > 0 && a.string === 0) return 1; let countDiff = b.count - a.count; if (countDiff !== 0) return countDiff; let letterDiff = a.letter.charCodeAt(0) - b.letter.charCodeAt(0); if (letterDiff !== 0) return letterDiff; return 0; }); Note how each sorting rule has been almost directly translated into logic. The watchful eye could find that the last sorting rule can be combined with the final return 0 statement, I've kept them separate for clarity. Another interesting part lies in the handling of the most important sorting rule, because it does two comparisons. This is needed because the rule is more specific than the others, since you don't want to actually sort higher string values first and lower values last, but only want to separate all the 0 string values to the end. Thus the extra logic is needed to avoid prematurely sorting a 2 infront of a 1. It might take a couple moments to let this code sink in, and to convince yourself that indeed this is the proper sorting logic you're looking for. At least I know it always takes me a couple moments. Keep in mind that a negative return value indicates that a goes first, a positive return value indicated that b goes first, and a return value of 0 indicates that you don't care about their poriorities. With that, look at the values calculated for each of the sorting rules, and check their signs for some simple sample cases. var a = { letter: 'a', count: 1, string: '0' }; var b = { letter: 'b', count: 1, string: '2' }; // -> `string` rule: b comes first, thus return a positive number. var a = { letter: 'a', count: 3, string: '1' }; var b = { letter: 'b', count: 1, string: '2' }; // -> `string` rule: inconclusive as neither is 0 (this is exactly why this rule has multiple conditionals being checked) // -> `count` rule: a comes first, thus return a negative number. var a = { letter: 'a', count: 1, string: '1' }; var b = { letter: 'b', count: 1, string: '2' }; // -> `string` rule: inconclusive as neither is 0 // -> `count` rule: inconclusive as counts are equal // -> `letter` rule: a comes first, thus return a negative number.
What do you use to sort arrays ? Oct 28, 2024
r/JavaScriptTips
last yr.
Sorting Arrays in JavaScript: toSorted() and sort() Dec 26, 2023
r/learnjavascript
2y ago
Guide to JavaScript Array Sort Method Nov 12, 2019
r/learnjavascript
6y ago
Array sorting explanation? Jun 19, 2022
r/learnjavascript
4y ago
More results from reddit.com
🌐
TypeOfNaN
typeofnan.dev › sort-array-objects-multiple-properties-javascript
How to sort an array of objects by multiple properties in JavaScript | TypeOfNaN
March 20, 2023 - This actually ends up being fairly similar to our last example except this time we sort each element of the array using a property: const arr = [ { name: 'Mike', age: 20 }, { name: 'Peter', age: 30 }, { name: 'Doris', age: 18 }, ]; arr.sort((a, b) => a.age - b.age); console.log(arr); /* [ { name: 'Doris', age: 18 }, { name: 'Mike', age: 20 }, { name: 'Peter', age: 30 }, ] */ Finally, we have our goal case: sorting objects by multiple properties.
Discussions

javascript - How to sort array of objects in 3 parts in JS? - Stack Overflow
I need to sort array of objects in the following way: 1st ones should be objects where favorites array includes only one item 2nd should be shown objects where favorites array is undefined or empty... More on stackoverflow.com
🌐 stackoverflow.com
August 19, 2020
javascript - Sort array of objects by string property value - Stack Overflow
Doesn't work for me, tried other solutions that does indeed work but this one doesn't. Attempted to sort by strings. 2022-03-31T22:17:50.263Z+00:00 ... The sort method can be modified to sort anything like an array of numbers, strings and even objects using a compare function. More on stackoverflow.com
🌐 stackoverflow.com
javaScript: sorting an array with multiple object/properties - General - The freeCodeCamp Forum
Hello every one, I am trying to build a card game using javaScript. I have used the .sort() method to reorder my deck of cards. My array is composed by a value: int number and a string: the card’s suit. I found a function to be included in the sort method (compare function) which should order ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
December 4, 2019
javascript - Sorting an array of objects by property values - Stack Overflow
Copy// sort by @date (descending) ... "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"} // expected: last element // { date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab" } ... Thanks to @Ozesh by his feedback, the issue related to properties with falsy values was fixed. ... In case you are sorting through numbers and you encounter a '0' in between the array of objects, you might ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › js › js_array_sort.asp
JavaScript Array Sort
This function loops through an ... } } return max; } ... Even if objects have properties of different data types, the sort() method can be used to sort the array....
🌐
Serhii Shramko
shramko.dev › home › snippets › sort an array of objects by multiple properties
How to Sort an Array of Objects by Multiple Properties in JavaScript
October 13, 2024 - Sorting an array of objects by multiple properties can be achieved using the Array.prototype.sort() method with a custom compare function.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-sort-array-of-objects-by-property-name-in-javascript
How to Sort an Array of Objects by Property Name in JavaScript
August 15, 2024 - While sorting objects based on a particular key, if the key is supposed to be a string, then make sure that the key has the data type String in all cases. A workaround to avoid potential bugs is to convert the key into a string in the sort() function. array.sort((a, b) => String(a.name).localeCompare(String(b.name))); When dealing with string properties, consider language and case sensitivity.
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › javascript › examples › sort array of objects by property values
JavaScript Program to Sort Array of Objects by Property ...
December 18, 2024 - Sorting arrays of objects by property values in JavaScript is a straightforward process once you master the use of the sort() method with appropriate comparator functions. From numeric and string properties to more complex multi-property sorting, ...
Top answer
1 of 16
5805

It's easy enough to write your own comparison function:

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

objs.sort( compare );

Or inline (c/o Marco Demaio):

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))

Or simplified for numeric (c/o Andre Figueiredo):

objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
2 of 16
1112

You can also create a dynamic sort function that sorts objects by their value that you pass:

function dynamicSort(property) {
    var sortOrder = 1;
    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a,b) {
        /* next line works with strings and numbers, 
         * and you may want to customize it to your needs
         */
        var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

So you can have an array of objects like this:

var People = [
    {Name: "Name", Surname: "Surname"},
    {Name:"AAA", Surname:"ZZZ"},
    {Name: "Name", Surname: "AAA"}
];

...and it will work when you do:

People.sort(dynamicSort("Name"));
People.sort(dynamicSort("Surname"));
People.sort(dynamicSort("-Surname"));

Actually this already answers the question. Below part is written because many people contacted me, complaining that it doesn't work with multiple parameters.

Multiple Parameters

You can use the function below to generate sort functions with multiple sort parameters.

function dynamicSortMultiple() {
    /*
     * save the arguments object as it will be overwritten
     * note that arguments object is an array-like object
     * consisting of the names of the properties to sort by
     */
    var props = arguments;
    return function (obj1, obj2) {
        var i = 0, result = 0, numberOfProperties = props.length;
        /* try getting a different result from 0 (equal)
         * as long as we have extra properties to compare
         */
        while(result === 0 && i < numberOfProperties) {
            result = dynamicSort(props[i])(obj1, obj2);
            i++;
        }
        return result;
    }
}

Which would enable you to do something like this:

People.sort(dynamicSortMultiple("Name", "-Surname"));

Subclassing Array

For the lucky among us who can use ES6, which allows extending the native objects:

class MyArray extends Array {
    sortBy(...args) {
        return this.sort(dynamicSortMultiple(...args));
    }
}

That would enable this:

MyArray.from(People).sortBy("Name", "-Surname");
🌐
Esri Community
community.esri.com › t5 › arcgis-javascript-maps-sdk-questions › javascript-array-of-objects-sorting-how-to-sort-by › td-p › 1329511
JavaScript Array of Objects Sorting: How to Sort by a Specific Object Property
December 13, 2023 - I have an array of objects in JavaScript, and I want to sort them based on a specific property of the objects. For example, I have an array of books, and each book object has properties like 'title', 'author', and 'publicationYear'. How can I sort this array of book objects alphabetically by ...
🌐
DEV Community
dev.to › markbdsouza › js-sort-an-array-of-objects-on-multiple-columns-keys-2bj1
JS: Sort an Array of Objects on multiple columns/keys - DEV Community
April 22, 2021 - That is if we want to sort by name first and then age · objs.sort((a,b)=> (a.name.localeCompare(b.name) || a.age - b.age)); ... Using the above logic, you can append how many ever sort columns you might need in the order you need them. ...
🌐
Flavio Copes
flaviocopes.com › home › javascript › sort an array of objects by a property in javascript
Sort an array of objects by a property in JavaScript
September 20, 2026 - The callback function could calculate other properties too, to handle the case where the color is the same, and order by a secondary property as well: list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 ) If you want to build a comparator like this without writing it by hand, try the sort comparator builder. ... Want me to talk about your product? You can sponsor this site. ... Enjoyed this? Grab my JavaScript Handbook for free.
🌐
Sabe
sabe.io › blog › javascript-sort-array-objects-property
How to Sort an Array of Objects by Property in JavaScript | Sabe
April 18, 2022 - Simply take advantage of the built-in sort method on arrays and you can sort an array of objects by any property by just comparing them.
🌐
DEV Community
dev.to › fpaghar › donesort-an-array-of-objects-ways-in-javascript-48hl
Sort an Array of Objects Ways in JavaScript - DEV Community
March 24, 2024 - This function alphabetical accepts an array arr, a getter function to extract the property for comparison, and an optional order parameter to specify the sorting direction. By default, it sorts in ascending order ('asc'), but it can be overridden to sort in descending order ('desc'). Sorting an array of objects based on specified properties and orders
🌐
Scaler
scaler.com › home › topics › sort an array of objects in javascript
Sort an Array of Objects in JavaScript - Scaler Topics
May 26, 2023 - We can sort an array of objects in JavaScript by using our built-in Arrays.sort() method, however, we must pass a custom function to our built-in sort method. The function is needed for the comparison of the properties based on which we want to sort our array of objects.
🌐
freeCodeCamp
forum.freecodecamp.org › general
javaScript: sorting an array with multiple object/properties - General - The freeCodeCamp Forum
December 4, 2019 - Hello every one, I am trying to build a card game using javaScript. I have used the .sort() method to reorder my deck of cards. My array is composed by a value: int number and a string: the card’s suit.
🌐
Reddit
reddit.com › r/javascripttips › day 57: how do you sort an array of objects by multiple properties in javascript?
r/JavaScriptTips on Reddit: Day 57: How Do You Sort an Array of Objects by Multiple Properties in JavaScript?
August 2, 2025 - https://javascript-tips.weebly.com/array-tips-complete.html · Search functions · r/DesignHomeGame • · upvotes · · comments · Did a little refactoring. r/Seablock • · 2 · upvotes · · comments · Data Structures in Python Visualized · r/datastructures • · upvotes · · comments · Day 47: Can You Sort an Array of Objects by a Property in JavaScript?
🌐
Atomizedobjects
atomizedobjects.com › blog › javascript › how-to-sort-an-array-of-objects-by-property-value-in-javascript
How to sort an array of objects by property value in JavaScript | Atomized Objects
To sort an array of objects by multiple properties, is pretty much the same as sorting an array by a single property value, except you need to decide on the property hierarchy in the order.