Home >Web Front-end >JS Tutorial >How to Sort Arrays of Objects by Attribute Using JQuery/JavaScript?
Sorting Object Arrays with JQuery/JavaScript
In JavaScript, you may encounter arrays of objects that require sorting based on specific attributes. To sort an array of objects by a specific attribute, such as "name" in your case, follow these steps:
Example:
Consider the following array of objects:
<code class="javascript">var array = [ { id: 1, name: "Alice", value: 10 }, { id: 2, name: "Bob", value: 15 }, { id: 3, name: "Carl", value: 5 } ];</code>
To sort the array by "name" in ascending order, use the following function:
<code class="javascript">function SortByName(a, b) { var aName = a.name.toLowerCase(); var bName = b.name.toLowerCase(); return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0)); }</code>
Apply the sorting using:
<code class="javascript">array.sort(SortByName);</code>
The resulting array will be sorted by "name" in ascending order:
<code class="javascript">[ { id: 3, name: "Carl", value: 5 }, { id: 1, name: "Alice", value: 10 }, { id: 2, name: "Bob", value: 15 } ]</code>
Regarding the Duplicate Question:
It appears that the question was previously closed as a duplicate because it was considered similar to a later question that received more attention. However, this question was asked earlier and should not have been marked as a duplicate.
The above is the detailed content of How to Sort Arrays of Objects by Attribute Using JQuery/JavaScript?. For more information, please follow other related articles on the PHP Chinese website!