• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Sorting Objects with a Primary and Secondary Property

Sorting Objects with a Primary and Secondary Property

Sorting Objects with a Primary and Secondary Property

When you sort an array and have several matches exact matches, it is handy to have a secondary property to sort by to break the tie. You can use the same approach as above, but with a little more logic. Inside the compareFunction, if the two properties have the same value (a zero compare value), then you can compare again by a secondary property.

let objects = [
  { name: "nop", value: 3 },
  { name: "NOP", value: 2 },
  { name: "ñop", value: 1 },
  { name: "abc", value: 3 },
  { name: "abc", value: 2 },
  { name: "äbc", value: 1 },
];
const collator = new Intl.Collator('en');
objects.sort((a, b) => {
    // Compare the strings via locale
    let diff = collator.compare(a.name, b.name);
    if (diff === 0) {
        // If the strings are equal compare the numbers
        return a.value - b.value;
    }
    return diff;
});
console.log(objects);
/*
[
    { "name": "abc", "value": 2 }, // name is same, sort by value
    { "name": "abc", "value": 3 }, // name is same, sort by value
    { "name": "äbc", "value": 1 },
    { "name": "nop", "value": 3 },
    { "name": "NOP", "value": 2 },
    { "name": "ñop", "value": 1 }
]
*/

Source

https://elijahmanor.com/byte/js-locale-sort

Miscellaneous

Related Snippets:

  • Resize an iframe to fit its content
  • Return every nth element in an array
  • How To Replace All Occurrences of a String in JavaScript
  • How To Check If a Variable is a String in JavaScript

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers