ترتيب مصفوفة JavaScript ()
أمثلة
ترتيب الصفيف:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
فرز الترتيب ثم عكسه:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
التعريف والاستخدام
يفرز sort()
عناصر المصفوفة.
الكتابة sort()
فوق المصفوفة الأصلية.
يفرز sort()
العناصر كسلاسل أبجدية وترتيب تصاعدي.
أنظر أيضا:
فرز مقارنة وظيفة
يعمل الفرز أبجديًا جيدًا مع السلاسل (تأتي كلمة "Apple" قبل "Banana").
ولكن ، يمكن أن يؤدي فرز الأرقام إلى نتائج غير صحيحة.
"25" أكبر من "100" ، لأن "2" أكبر من "1".
يمكنك إصلاح هذا من خلال توفير "وظيفة مقارنة" (انظر الأمثلة أدناه).
بناء الجملة
array.sort(compareFunction)
المعلمات
Parameter | Description |
compareFunction |
Optional. A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments:
When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. Example: The sort function will sort 40 as a value lower than 100. When comparing 40 and 100, sort() calls the function(40,100). The function calculates 40-100, and returns -60 (a negative value). |
قيمة الإرجاع
المصفوفة مع العناصر مرتبة. |
مزيد من الأمثلة
فرز الأرقام بترتيب تصاعدي:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
ترتيب الأرقام بترتيب تنازلي:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
ابحث عن أقل قيمة:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order
points.sort(function(a, b){return a-b});
let lowest = points[0];
ابحث عن أعلى قيمة:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in descending order:
points.sort(function(a, b){return b-a});
let lowest = points[0];
ابحث عن أعلى قيمة:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order:
points.sort(function(a, b){return a-b});
let highest = points[points.length-1];
دعم المتصفح
sort()
هي إحدى ميزات ECMAScript1 (ES1).
ES1 (JavaScript 1997) مدعوم بالكامل في جميع المتصفحات:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |