Home  >  Article  >  Web Front-end  >  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
Mary-Kate OlsenOriginal
2024-10-23 11:59:02113browse

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>

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!

Statement:
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