0
0
Javascriptprogramming~20 mins

Reduce method in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Reduce Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this reduce example?
Consider the following JavaScript code using the reduce method. What will be printed to the console?
Javascript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, val) => acc + val, 0);
console.log(sum);
Aundefined
B24
C10
DTypeError
Attempts:
2 left
πŸ’‘ Hint
Think about how reduce adds each number starting from 0.
❓ Predict Output
intermediate
2:00remaining
What does this reduce code output?
Look at this code that uses reduce to find the longest word in an array. What will it print?
Javascript
const words = ['cat', 'elephant', 'dog', 'hippopotamus'];
const longest = words.reduce((a, b) => a.length > b.length ? a : b);
console.log(longest);
A"hippopotamus"
BTypeError
C"dog"
D"elephant"
Attempts:
2 left
πŸ’‘ Hint
Reduce compares lengths and keeps the longer word.
❓ Predict Output
advanced
2:00remaining
What is the output of this reduce with objects?
This code uses reduce to count how many times each color appears. What is the output?
Javascript
const colors = ['red', 'blue', 'red', 'green', 'blue', 'blue'];
const count = colors.reduce((acc, color) => {
  acc[color] = (acc[color] || 0) + 1;
  return acc;
}, {});
console.log(count);
A{"red":3,"blue":2,"green":1}
B{"red":1,"blue":1,"green":1}
CTypeError
D{"red":2,"blue":3,"green":1}
Attempts:
2 left
πŸ’‘ Hint
Each color is counted by adding 1 to its current count.
❓ Predict Output
advanced
2:00remaining
What error does this reduce code cause?
What error will this code produce when run?
Javascript
const arr = [];
const result = arr.reduce((a, b) => a + b);
console.log(result);
ASyntaxError
BTypeError: Reduce of empty array with no initial value
Cundefined
D0
Attempts:
2 left
πŸ’‘ Hint
Think about what happens when reduce has no initial value and the array is empty.
🧠 Conceptual
expert
2:00remaining
Which option produces the product of all numbers using reduce?
You want to multiply all numbers in an array using reduce. Which option correctly does this?
Aarr.reduce((acc, val) => acc * val, 1)
Barr.reduce((acc, val) => acc + val, 1)
Carr.reduce((acc, val) => acc * val)
Darr.reduce((acc, val) => val * val, 1)
Attempts:
2 left
πŸ’‘ Hint
Start with 1 and multiply each value to the accumulator.