Lesson 16 / الدرس 16
Array methods: find, filter, map, reduce / دوال المصفوفات: find وfilter وmap وreduce
Four methods replace most of the loops you would otherwise write, and each one says what it is doing in its name. This is where JavaScript starts reading like a description of the result.
أربع دوال تحل محل معظم الحلقات التي كنت ستكتبها، وكل واحدة تقول ما تفعله في اسمها. وهنا تبدأ JavaScript في القراءة كوصف للنتيجة.
| Method | Answers | Gives back |
|---|---|---|
| find | Which one matches? | The first match, or undefined |
| filter | Which ones match? | A new, shorter array |
| map | What does each become? | A new array of the same length |
| reduce | What do they add up to? | A single value |
| some | Is any of them true? | true or false |
| every | Are all of them true? | true or false |
| sort | In what order? | The SAME array, reordered |
Every one of these except sort leaves the original alone and hands you something new. sort is the exception and it changes the array in place, which surprises people at exactly the wrong moment.
sort تترك الأصل وتسلّمك شيئًا جديدًا. وsort هي الاستثناء وتغيّر المصفوفة في موضعها، وهذا يفاجئ الناس في اللحظة الخطأ بالضبط.The same job, both ways
WITH A LOOP
const cheap = [];
for (const p of products) {
if (p.price < 100) { cheap.push(p); }
}
WITH FILTER
const cheap = products.filter(p => p.price < 100);
p => p.price < 100 part is a small function — lesson 18 explains the shape — and for now read it as "given a p, is its price under 100". Run the demonstration.
p => p.price < 100 دالة صغيرة — والدرس 18 يشرح الشكل — واقرأه الآن "بمعطى p، أسعره دون 100".شغّل العرض.Chaining them
Because filter and map each return a new array, you can put the next one straight after: products.filter(p => p.inStock).map(p => p.name).join(", ") reads left to right as "the ones in stock, their names, joined". A chain of three is usually clearer than the loop it replaces; a chain of six is usually worse, and that is the point to give the middle result a name.
filter وmap يعيدان مصفوفة جديدة، تستطيع وضع التالي مباشرة بعده: فـproducts.filter(p => p.inStock).map(p => p.name).join(", ") تُقرأ من اليسار لليمين "الموجودة في المخزن، وأسماؤها، موصولة". وسلسلة من ثلاث أوضح عادةً من الحلقة التي تحل محلها؛ وسلسلة من ست أسوأ عادةً، وتلك هي النقطة التي تعطي فيها النتيجة الوسطى اسمًا.sort فخّان. فهي تغيّر المصفوفة الأصلية لا تعيد جديدة، فـconst sorted = items.sort() يعيد ترتيب items أيضًا — انسخ أولًا بـ[...items].sort() إن كان ذلك يهم. وهي ترتب نصًا افتراضيًا، فـ[10, 9, 100].sort() تعطي [10, 100, 9]. وللأرقام يجب تمرير مقارنة: .sort((a, b) => a - b).
reduce is the one people find hardest, and it is worth one careful sentence: it walks the list carrying a running value, and you say how each item changes it. The second argument is where that running value starts. reduce((sum, p) => sum + p.price, 0) starts at 0 and adds each price. Forgetting the starting value is the commonest reduce bug, and on an empty list it throws.
reduce هي التي يجدها الناس أصعب، وتستحق جملة واحدة متأنية: فهي تمشي في القائمة حاملة قيمة جارية، وتقول أنت كيف يغيّرها كل عنصر. والوسيط الثاني هو حيث تبدأ تلك القيمة. فـreduce((sum, p) => sum + p.price, 0) تبدأ من 0 وتضيف كل سعر. ونسيان قيمة البدء أشيع عيب في reduce، وعلى قائمة فارغة يرمي خطأً.filter؛ والعدد نفسه مغيَّرًا map؛ وعنصر واحد find؛ وقيمة واحدة reduce؛ ونعم أو لا some أو every. وسؤال "ما شكل الجواب" ينتقي الصحيحة كل مرة.Try it live / جرّب بنفسك
Check yourself / اختبر نفسك
1. Which method gives back a shorter array?
map always returns the same number of items. Choosing by the shape of the answer picks the right method every time.
map تعيد العدد نفسه دائمًا. واختيار بشكل الجواب ينتقي الدالة الصحيحة كل مرة.
2.
What does [10, 9, 100].sort() give?
[10, 9, 100].sort()؟For numbers you must pass a comparison: .sort((a, b) => a - b). It also reorders the original array rather than returning a new one.
.sort((a, b) => a - b). وهي تعيد ترتيب المصفوفة الأصلية لا تعيد جديدة.
3.
What is the second argument to reduce?
reduce؟Forgetting it is the commonest reduce bug, and on an empty list it throws rather than returning zero.
reduce، وعلى قائمة فارغة يرمي خطأً بدل إعادة صفر.Score / النتيجة: 0 / 3
Your task / مهمتك
Take a list of at least eight products, each with a name, a price and whether it is in stock. Answer five questions with array methods rather than loops: which are in stock, what the total value of the stock is, whether anything costs more than 500, the name of the first item under 50, and all the names as one sorted line of text. Then rewrite one of them as a plain loop and say which reads better.
خذ قائمة من ثمانية منتجات على الأقل، لكل واحد اسم وسعر وهل هو في المخزن. وأجب خمسة أسئلة بدوال المصفوفات لا بالحلقات: أيها في المخزن، وكم القيمة الكلية للمخزون، وهل شيء يزيد سعره على 500، واسم أول صنف دون 50، وكل الأسماء في سطر نص واحد مرتب. ثم أعد كتابة واحدة منها حلقةً عادية وقل أيهما يُقرأ أفضل.
- Eight products with three fields each ثمانية منتجات بثلاثة حقول لكل واحد
- Five questions answered with methods, not loops خمسة أسئلة مُجابة بالدوال لا بالحلقات
- A sort that works correctly on the values you sorted ترتيب يعمل بشكل صحيح على القيم التي رتّبتها
- One rewritten as a loop, with a judgement واحدة معادة حلقةً مع حكم