Sort an Array of Objects in JavaScript with the sort() method
Feb 10, 2025 am 11:52 AMJavaScript native Array.sort
methods can also easily sort object arrays! This article will demonstrate how to sort arrays of objects containing strings, numbers, and dates using the Array.sort
method, and provide practical tips for handling case sensitivity, array copying, and common libraries.
Core points
- JavaScript's native
Array.sort
method can be used to sort object arrays, using comparison functions to define sorting logic for strings, numbers, dates, and other properties. - The comparison function in JavaScript returns a number to determine the sort order. If the integer is less than 0, the first element appears before the second element; if it is greater than 0, the second element appears before the first element; if it is exactly 0, the original order remains.
- can create a dynamic sorting function that can sort an array of objects using strings or numeric values. This function can be sorted ascending or descending according to the specified key. The
- JavaScript's
Array.sort
method will modify its sorted original array. To avoid this, you can use theArray.slice
method or extension operator to create a new array instance and sort it.
Basic array sorting (and why it doesn't work)
By default, the JavaScript Array.sort
method converts each element in the array that needs to be sorted into a string and compares it in Unicode code point order.
const foo = [9, 1, 4, 'zebroid', 'afterdeck']; foo.sort(); // 返回 [ 1, 4, 9, 'afterdeck', 'zebroid' ] const bar = [5, 18, 32, new Set, { user: 'Eleanor Roosevelt' }]; bar.sort(); // 返回 [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]
You may be curious why 32 is before 5? It seems unreasonable, right? Actually, it is not the case. This is because each element in the array is first converted to a string, and "32" is before "5" in Unicode order.
Use Array.sort
only to sort object arrays cannot be efficiently sorted. Fortunately, the sort
method accepts an optional compareFunction
parameter that we can use to sort the object array.
How to sort object arrays in JavaScript
To sort an array of objects, use the sort()
method with a comparison function. Comparison functions apply rules and sort the arrays according to our custom logic. They allow us to sort the array of objects by strings, integers, dates, or any other custom attributes. We will explain how comparison functions work later in this article.
In this demo, we will use an array of singers and sort them alphabetically by their band name:
const singers = [ { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 }, { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 }, { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 }, { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 }, ];
The following comparison function compares the (capsular) name of each band:
function compare(a, b) { // 使用 toUpperCase() 忽略字符大小寫 const bandA = a.band.toUpperCase(); const bandB = b.band.toUpperCase(); let comparison = 0; if (bandA > bandB) { comparison = 1; } else if (bandA < bandB) { comparison = -1; } return comparison; } singers.sort(compare); /* 返回 [ { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 }, { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 }, { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 }, { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 } ] */
To invert the sort order, you can invert the return value of the comparison function:
const foo = [9, 1, 4, 'zebroid', 'afterdeck']; foo.sort(); // 返回 [ 1, 4, 9, 'afterdeck', 'zebroid' ] const bar = [5, 18, 32, new Set, { user: 'Eleanor Roosevelt' }]; bar.sort(); // 返回 [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]
How does comparison function work
The comparison function returns a number used to determine the sort order by comparing its two inputs (a and b). Simply put, if the integer is less than 0, a appears before b; if it is greater than 0, b appears before a; if it is exactly 0, the original order is maintained. But how you determine this number depends on you.
Let's look at a simple array of numbers:
const singers = [ { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 }, { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 }, { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 }, { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 }, ];
We can do some refactoring of it, because subtracting b from a will also return us the value. This comparison function sorts array of numbers from small to large:
function compare(a, b) { // 使用 toUpperCase() 忽略字符大小寫 const bandA = a.band.toUpperCase(); const bandB = b.band.toUpperCase(); let comparison = 0; if (bandA > bandB) { comparison = 1; } else if (bandA < bandB) { comparison = -1; } return comparison; } singers.sort(compare); /* 返回 [ { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 }, { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 }, { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 }, { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 } ] */
It can also be represented as an arrow function without defining the comparison function elsewhere:
function compare(a, b) { // ... // 通過乘以 -1 反轉(zhuǎn)返回值 return comparison * -1; }
If you are not familiar with arrow functions, you can read more about them here: Arrow functions in JavaScript.
As you can see, the comparison function can be written in many ways, and the sort()
method will be executed as directed.
Create a dynamic sorting function
Let's complete our previous example to make it more dynamic. Let's create a sorting function that you can use to sort an array of objects whose values ??are strings or numbers. This function has two parameters - the key we want to sort and the order of the results (i.e. ascending or descending):
const nums = [79, 48, 12, 4]; function compare(a, b) { if (a > b) return 1; if (b > a) return -1; return 0; } nums.sort(compare); // => 4, 12, 48, 79
Here's how to use it:
function compareNums(a, b) { return a - b; } nums.sort(compareNums)
In the above code, the hasOwnProperty
method is used to check whether the specified attribute is defined on each object and is not inherited through the prototype chain. If it is not defined on both objects, the function returns 0, which causes the sorting order to remain unchanged (i.e. the objects remain unchanged relative to each other).
typeof
operator is also used to check the type of property value. This allows the function to determine the correct way to sort the array. For example, if the value of the specified property is a string, the toUpperCase
method is used to convert all characters to uppercase, so character case is ignored when sorting.
You can adjust the above functions to suit other data types, as well as any other needs your script may need.
Popular array sorting library
You may not have the time or patience to create your own sorting functions in native JavaScript. Time is money, and the code takes time. Fortunately, there are a variety of libraries that can meet all your array sorting needs. Here is a short list of some auxiliary libraries containing sorting functions...no particular order ;)
- array-sort
- underscore.js
- sugarjs
- lodash
Quick Tips: Sort object array by date
To sort the array of objects by date string, you just need to provide a comparison function that first parses the date strings and subtracts them from each other:
nums.sort((a, b) => a - b);
Quick Tips: Sorting without modifying the array
Unlike many other JavaScript array functions, Array.sort
is one of the methods that will change (modify) the array of sorts instead of returning a new array. To avoid this, you can create a new instance of the array to be sorted and modify it. This can be used to create a copy of the array using an array method or an extension syntax.
const foo = [9, 1, 4, 'zebroid', 'afterdeck']; foo.sort(); // 返回 [ 1, 4, 9, 'afterdeck', 'zebroid' ] const bar = [5, 18, 32, new Set, { user: 'Eleanor Roosevelt' }]; bar.sort(); // 返回 [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]
Create an array copy using Array.slice
:
const singers = [ { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 }, { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 }, { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 }, { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 }, ];
Alternatively, you can use the extension operator to get the same effect:
function compare(a, b) { // 使用 toUpperCase() 忽略字符大小寫 const bandA = a.band.toUpperCase(); const bandB = b.band.toUpperCase(); let comparison = 0; if (bandA > bandB) { comparison = 1; } else if (bandA < bandB) { comparison = -1; } return comparison; } singers.sort(compare); /* 返回 [ { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 }, { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 }, { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 }, { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 } ] */
In both cases, the output is the same and can be used before sorting any object array.
function compare(a, b) { // ... // 通過乘以 -1 反轉(zhuǎn)返回值 return comparison * -1; }
Quick Tips: Sorting arrays by strings in case insensitive manner
In our previous example, we wanted to sort an array of objects with values ??that are strings or numbers. However, if you know you will only process objects whose values ??are strings, you can use JavaScript's localeCompare
method to organize your code.
This method returns a number indicating whether the string is before, after or the same as the given string in the sort order. It allows case-insensitive sorting of arrays:
const nums = [79, 48, 12, 4]; function compare(a, b) { if (a > b) return 1; if (b > a) return -1; return 0; } nums.sort(compare); // => 4, 12, 48, 79
In terms of our compareValues
function, this means we can write this way:
function compareNums(a, b) { return a - b; } nums.sort(compareNums)
You can read more about localeCompare
on MDN.
Conclusion
That's it - a short introduction to sorting arrays of objects using native JavaScript. Although many libraries provide this dynamic sorting capability, as shown, it is not difficult to implement this capability yourself. In addition, it is also helpful to know what is happening behind the scenes.
To build a more comprehensive understanding of the foundation of native JavaScript, we recommend JavaScript: from beginners to ninjas. Learn JavaScript from scratch, including ES6, and practice your new knowledge through a range of projects.
FAQ on how to sort object arrays in JavaScript
Can you sort object arrays in JavaScript?
Yes. JavaScript provides built-in methods to help sort array elements.
How to sort object arrays in JavaScript?
You can use the Array.prototype.sort()
method and provide a custom comparison function to sort the array of objects in JavaScript. The comparison function should compare the relevant properties of each object.
How to sort an array of objects in JavaScript by key?
You can dynamically sort the array of objects by providing keys to the comparison function. This allows you to sort by various attributes. To sort the array of objects by a specific key (properties) in JavaScript, you can use the Array.prototype.sort()
method and a custom comparison function that compares the values ??of the desired key for each object.
How to dynamically sort object arrays in JavaScript?
To dynamically sort arrays of objects in JavaScript based on keys (properties) determined at runtime, you can create a function that accepts arrays and keys as parameters. This function can then use the Array.prototype.sort()
method as well as a custom comparison function to access the dynamically provided keys for sorting.
Is there any library that simplifies the sorting of object arrays? Yes, libraries like Lodash and Underscore.js provide utility functions for sorting arrays of objects with additional functionality and convenience. However, JavaScript's built-in sort()
methods are usually sufficient to meet basic sorting needs.
Is sorting by object key case sensitive? Yes, by default, sort by object key is case sensitive. You can use the localeCompare()
method to perform case-insensitive sorting.
The above is the detailed content of Sort an Array of Objects in JavaScript with the sort() method. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.
