Home > Web Front-end > JS Tutorial > How to Sort an Array of Objects by a Specified Attribute in JavaScript?

How to Sort an Array of Objects by a Specified Attribute in JavaScript?

Mary-Kate Olsen
Release: 2024-10-23 11:59:02
Original
211 people have browsed it

How to Sort an Array of Objects by a Specified Attribute in JavaScript?

Sorting an Array of Objects by a Specified Attribute in JavaScript

Objects within arrays can often require rearrangement based on specific attributes for data manipulation. In this particular case, the objective is to sort an array of objects in ascending order by their "name" attribute.

To achieve this, one can utilize a custom sorting function, as illustrated below:

<code class="js">// Custom sorting function
function SortByName(a, b) {
  // Convert both names to lowercase for case-insensitive comparison
  var aName = a.name.toLowerCase();
  var bName = b.name.toLowerCase();

  // Return the result of the comparison based on the sort order
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

// Sort the array using the custom function
array.sort(SortByName);</code>
Copy after login

By passing this function as an argument to the sort() method, the array of objects will be sorted alphabetically based on the "name" attribute. It is imperative to remember that this sorting method will produce a case-insensitive result by converting both names to lowercase for comparison.

The above is the detailed content of How to Sort an Array of Objects by a Specified Attribute in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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