What is the reduce() method used for in JavaScript?
The reduce() method executes a reducer function on each element of the array, resulting in a single output value.
How do you sum an array of numbers using reduce()?
numbers.reduce((acc, n) => acc + n, 0)
How do you multiply all numbers in an array using reduce()?
numbers.reduce((acc, n) => acc * n, 1)
How can you find the maximum value in an array using reduce()?
numbers.reduce((max, n) => n > max ? n : max, numbers[0])
How can you find the minimum value in an array using reduce()?
numbers.reduce((min, n) => n < min ? n : min, numbers[0])
How do you concatenate an array of strings using reduce()?
strings.reduce((acc, s) => acc + s, ‘’)
How can you count elements in an array using reduce()?
arr.reduce(count => count + 1, 0)
How do you convert an array of numbers to the sum of squares using reduce()?
numbers.reduce((acc, n) => acc + n * n, 0)
How can you create a comma-separated string from an array using reduce()?
arr.reduce((acc, x) => acc ? acc + ‘,’ + x : x, ‘’)
How do you reverse an array using reduce()?
arr.reduce((acc, x) => [x, …acc], [])
How can you remove duplicates from an array using reduce()?
arr.reduce((acc, x) => acc.includes(x) ? acc : […acc, x], [])
How do you count the frequency of elements in an array using reduce()?
arr.reduce((acc, x) => { acc[x] = (acc[x] || 0) + 1; return acc; }, {})
How can you group objects by a property using reduce()?
arr.reduce((acc, obj) => { (acc[obj.key] ||= []).push(obj); return acc; }, {})
How do you flatten a 2D array using reduce()?
arr.reduce((acc, x) => acc.concat(x), [])
How can you find the average of numbers in an array using reduce()?
arr.reduce((acc, n, _, { length }) => acc + n/length, 0)
How do you partition an array into even and odd numbers using reduce()?
arr.reduce((acc, n) => { acc[n%2?’odd’:’even’].push(n); return acc; }, {even:[], odd:[]})
How can you find unique characters in a string using reduce()?
str.split(‘’).reduce((acc, c) => acc.includes(c) ? acc : acc + c, ‘’)
How do you merge an array of objects into one using reduce()?
arr.reduce((acc, obj) => ({…acc, …obj}), {})
How can you count vowels in a string using reduce()?
str.split(‘’).reduce((acc, c) => ‘aeiou’.includes(c)?acc+1:acc, 0)
How do you find the longest word in an array using reduce()?
arr.reduce((longest, w) => w.length > longest.length ? w : longest, ‘’)
How can you check if all elements are positive using reduce()?
arr.reduce((acc, n) => acc && n > 0, true)
How do you convert an array of key-value pairs to an object using reduce()?
arr.reduce((obj,[k,v]) => (obj[k]=v,obj),{})
How can you implement map() using reduce()?
arr.reduce((acc, x) => […acc, x*2], [])
How can you implement filter() using reduce()?
arr.reduce((acc, x) => x>0?[…acc,x]:acc, [])