Array Reduce Object in JavaScript
Level 4195 keystrokes
reduce() can transform an array into an object, useful for counting occurrences.
JavaScript code
// Create an array with duplicate fruits1const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];// Use reduce to count occurrences// acc is the accumulator (starts as empty object {})2const count = fruits.reduce((acc, fruit) => { // If fruit exists, increment; otherwise set to 1 // || 0 handles undefined case3 acc[fruit] = (acc[fruit] || 0) + 1; // Always return the accumulator4 return acc;5}, {});// Print { apple: 3, banana: 2, orange: 1 }6console.log(count);Output
{ apple: 3, banana: 2, orange: 1 }Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
"× 12,× 7;× 5(× 4)× 4=× 4[× 3]× 3.× 2{× 2