Complete the code to sum all numbers in the array using reduce.
const numbers = [1, 2, 3, 4]; const total = numbers.reduce((acc, curr) => acc [1] curr, 0); console.log(total);
The reduce method combines all elements by adding them together using the + operator.
Complete the code to find the product of all numbers using reduce.
const nums = [2, 3, 4]; const product = nums.reduce((acc, curr) => acc [1] curr, 1); console.log(product);
To multiply all numbers, use the * operator inside reduce.
Fix the error in the reduce function to concatenate all strings in the array.
const words = ['I', 'love', 'coding']; const sentence = words.reduce((acc, curr) => acc [1] curr); console.log(sentence);
Strings are combined using the + operator to concatenate them.
Fill both blanks to create an object counting how many times each word appears.
const words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const count = words.reduce((acc, curr) => { acc[curr] = (acc[curr] [1] 0) [2] 1; return acc; }, {}); console.log(count);
The expression acc[curr] = (acc[curr] || 0) + 1; means if acc[curr] exists, use it; otherwise, use 0, then add 1.
Fill all three blanks to create a new object with uppercase keys and values doubled if greater than 10.
const data = {a: 5, b: 15, c: 8};
const result = Object.entries(data).reduce((acc, [1]) => {
const [key, value] = [2];
if (value [3] 10) {
acc[key.toUpperCase()] = value * 2;
}
return acc;
}, {});
console.log(result);We use item as the parameter for the reduce callback and destructure it to get key and value. The condition checks if value > 10.