Home > Web Front-end > JS Tutorial > Sort an Array of Objects in JavaScript with the sort() method

Sort an Array of Objects in JavaScript with the sort() method

William Shakespeare
Release: 2025-02-10 11:52:17
Original
611 people have browsed it

Sort an Array of Objects in JavaScript with the sort() method

JavaScript 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 the Array.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 {} ]
Copy after login
Copy after login
Copy after login

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 },
];
Copy after login
Copy after login
Copy after login

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 }
] */
Copy after login
Copy after login
Copy after login

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 {} ]
Copy after login
Copy after login
Copy after login

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 },
];
Copy after login
Copy after login
Copy after login

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 }
] */
Copy after login
Copy after login
Copy after login

It can also be represented as an arrow function without defining the comparison function elsewhere:

function compare(a, b) {
  // ...
  // 通过乘以 -1 反转返回值
  return comparison * -1;
}
Copy after login
Copy after login

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
Copy after login
Copy after login

Here's how to use it:

function compareNums(a, b) {
  return a - b;
}
nums.sort(compareNums)
Copy after login
Copy after login

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).

The

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);
Copy after login

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 {} ]
Copy after login
Copy after login
Copy after login

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 },
];
Copy after login
Copy after login
Copy after login

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 }
] */
Copy after login
Copy after login
Copy after login

In both cases, the output is the same and can be used before sorting any object array.

function compare(a, b) {
  // ...
  // 通过乘以 -1 反转返回值
  return comparison * -1;
}
Copy after login
Copy after login

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
Copy after login
Copy after login

In terms of our compareValues function, this means we can write this way:

function compareNums(a, b) {
  return a - b;
}
nums.sort(compareNums)
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template