目錄
Sorting Numbers in Ascending Order
Sorting Strings Alphabetically
Handling Mixed or Complex Data Types
首頁 web前端 js教程 如何按屬性值對對象進行排序?

如何按屬性值對對象進行排序?

Jul 02, 2025 am 01:08 AM
陣列 對象排序

在JavaScript中,可以通过提供一个比较函数使用.sort()方法按属性值排序对象数组。对于数值属性的升序排列,用a.age - b.age;降序则用b.age - a.age;字符串属性排序需使用localeCompare()方法,并可调整大小写敏感性;处理混合或复杂数据类型时应规范化值、妥善处理undefined或null,并可借助辅助函数,例如通过getOrderValue返回标准化排序值进行计算,从而实现数组按特定属性正确排序。

How to sort an array of objects by a property value?

You can sort an array of objects by a property value in JavaScript using the .sort() method. The trick is to provide a comparison function that tells JavaScript how to compare two objects based on the desired property.


Sorting Numbers in Ascending Order

To sort an array of objects by a numeric property, like age, you can subtract one value from the other in the comparator function:

const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
];

people.sort((a, b) => a.age - b.age);

This will sort the array so the person with the lowest age comes first.
If you want descending order instead, just flip the subtraction: b.age - a.age.


Sorting Strings Alphabetically

When sorting by string properties like name, you need to use comparison logic suitable for strings — usually with localeCompare():

const people = [
  { name: 'Zoe', age: 28 },
  { name: 'John', age: 32 },
  { name: 'Anna', age: 25 }
];

people.sort((a, b) => a.name.localeCompare(b.name));
  • localeCompare() handles alphabetical ordering correctly, including case sensitivity and special characters.
  • If you don’t care about case, you might normalize the strings before comparing:
    a.name.toLowerCase().localeCompare(b.name.toLowerCase())

Handling Mixed or Complex Data Types

Sometimes the values you're comparing may not be straightforward — maybe some are numbers, some are strings, or even nested values.

In those cases, it’s good practice to:

  • Normalize values before comparison
  • Handle undefined or null values gracefully
  • Use a helper function inside .sort() if needed

Example:

const items = [
  { label: 'Item C', order: 'last' },
  { label: 'Item A', order: 1 },
  { label: 'Item B', order: 3 }
];

const getOrderValue = (item) => {
  if (typeof item.order === 'number') return item.order;
  if (item.order === 'last') return Infinity;
  return 0;
};

items.sort((a, b) => getOrderValue(a) - getOrderValue(b));

This helps when your data isn't consistent across all objects.


Sorting arrays of objects by a property doesn’t have to be tricky — once you know how to use .sort() with a custom comparator, you can handle most common scenarios pretty easily. Just remember to adjust your comparison logic depending on whether you're working with numbers, strings, or mixed data types.

以上是如何按屬性值對對象進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1605
29
PHP教程
1510
276
PHP數組深度複製的藝術:使用不同方法完美複製 PHP數組深度複製的藝術:使用不同方法完美複製 May 01, 2024 pm 12:30 PM

PHP中深度複製數組的方法包括:使用json_decode和json_encode進行JSON編碼和解碼。使用array_map和clone進行深度複製鍵和值的副本。使用serialize和unserialize進行序列化和反序列化。

PHP 陣列鍵值翻轉:不同方法的效能比較分析 PHP 陣列鍵值翻轉:不同方法的效能比較分析 May 03, 2024 pm 09:03 PM

PHP數組鍵值翻轉方法效能比較顯示:array_flip()函數在大型數組(超過100萬個元素)下比for迴圈效能更優,耗時更短。手動翻轉鍵值的for迴圈方法耗時相對較長。

深度複製PHP數組的最佳實踐:探索高效的方法 深度複製PHP數組的最佳實踐:探索高效的方法 Apr 30, 2024 pm 03:42 PM

在PHP中執行陣列深度複製的最佳實踐是:使用json_decode(json_encode($arr))將陣列轉換為JSON字串,然後再轉換回陣列。使用unserialize(serialize($arr))將陣列序列化為字串,然後將其反序列化為新陣列。使用RecursiveIteratorIterator迭代器對多維數組進行遞歸遍歷。

PHP 數組分組函數在資料整理的應用 PHP 數組分組函數在資料整理的應用 May 04, 2024 pm 01:03 PM

PHP的array_group_by函數可依鍵或閉包函數將陣列中的元素分組,傳回關聯數組,其中鍵為組名,值是屬於該組的元素數組。

PHP 陣列分組函數在尋找重複元素中的作用 PHP 陣列分組函數在尋找重複元素中的作用 May 05, 2024 am 09:21 AM

PHP的array_group()函數可用來按指定鍵對陣列進行分組,以尋找重複元素。函數透過以下步驟運作:使用key_callback指定分組鍵。可選地使用value_callback確定分組值。對分組元素進行計數並識別重複項。因此,array_group()函數對於尋找和處理重複元素非常有用。

數組可以當函數參數嗎? 數組可以當函數參數嗎? Jun 04, 2024 pm 04:30 PM

是的,在許多程式語言中,數組可以作為函數參數,函數將對其中儲存的資料執行操作。例如C++中的printArray函數可以列印數組中的元素,而Python中的printArray函數可以遍歷數組並列印其元素。這些函數對陣列所做的修改也會反映在呼叫函數中的原始數組中。

PHP 中如何根據數組鍵名長度進行排序,保留鍵名? PHP 中如何根據數組鍵名長度進行排序,保留鍵名? May 02, 2024 pm 01:03 PM

透過uksort()函數和自訂比較函數compareKeyLengths,可以根據陣列鍵名長度對PHP陣列進行排序,同時保留鍵名。比較函數計算鍵名長度差並傳回一個整數,uksort()根據該整數排序數組。此外,實戰案例示範如何對來自資料庫的記錄按欄位名稱長度排序。

使用PHP集合類別高效計算數組交集和並集 使用PHP集合類別高效計算數組交集和並集 May 01, 2024 pm 09:06 PM

使用PHP集合類別可有效率地計算陣列交集和並集,具體步驟如下:利用intersect()方法計算交集:同時出現在兩個陣列中的元素。利用union()方法計算並集:出現在任一個陣列中的元素。實戰案例:透過比較購物車內容,了解使用者重疊商品和獨一無二商品。

See all articles