• 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 by an Object Property

Sorting by an Object Property

Sorting by an Object Property

You can sort arrays of objects. In this case we leverage the collator.compare method and pass along the properties that we want to sort by.

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) => collator.compare(a.name, b.name));
console.log(objects);
/*
[
    { "name": "abc", "value": 3 },
    { "name": "abc", "value": 2 },
    { "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:

  • Copy text to the clipboard
  • How To Copy To The Clipboard Using JavaScript
  • Replace a portion of a string with something else
  • Optional Chaining to Prevent Crashes

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us