Array Methods: map, filter, aur reduce
map() aur filter() woh do array methods hain jo aap baar baar istemal karoge — aksar Python developers bilkul isi tarah ki tabdeeli ke liye list comprehensions istemal karte hain, aur yeh JavaScript ka equivalent hain.
const numbers = [1, 2, 3, 4, 5]; const squared = numbers.map((x) => x * x); console.log(squared); const evens = numbers.filter((x) => x % 2 === 0); console.log(evens);
[ 1, 4, 9, 16, 25 ] [ 2, 4 ]
map() har item ko badalta hai aur same length ka naya array wapas karta hai. filter() sirf woh items rakhta hai jin ke liye function true wapas karta hai, isliye result original se chhota ho sakta hai. In mein se koi bhi original array ko nahi badalta.
reduce — har item ko ek value mein jorna
const numbers = [1, 2, 3, 4, 5]; const total = numbers.reduce((sum, x) => sum + x, 0); console.log(total);
15
reduce() array mein se guzarta hai, ek accumulator (sum) ko ek item se doosre tak le jaate hue. 0 accumulator ki shuruati value hai. Yahan yeh bas sab kuch jor raha hai, lekin reduce() array se koi bhi single result bana sakta hai — ek total, ek maximum, ya ek poora naya object bhi.
Aage: exception handling — apne program ko crash hone dene ke bajaye errors ko sahi tareeqe se sambhalna.
Practice Exercise
1 se 4 tak numbers ke cubes ka array banane ke liye .map() istemal karo, phir use print karo.