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 في القراءة كوصف للنتيجة.

MethodAnswersGives back
findWhich one matches?The first match, or undefined
filterWhich ones match?A new, shorter array
mapWhat does each become?A new array of the same length
reduceWhat do they add up to?A single value
someIs any of them true?true or false
everyAre all of them true?true or false
sortIn 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.

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);
The second is one line and says what it produces rather than how. The 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.

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.

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.

Try it live / جرّب بنفسك

Preview / المعاينة

Check yourself / اختبر نفسك

1. Which method gives back a shorter array?

2. What does [10, 9, 100].sort() give?

3. What is the second argument to reduce?

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 واحدة معادة حلقةً مع حكم
How do you want to submit? / كيف تريد التسليم؟