-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReduceFunction.js
36 lines (27 loc) · 1.11 KB
/
ReduceFunction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* const numbers = [1, 2, 3, 4, 5];
// Reducer function to sum the elements
const sum = numbers.reduce((accumulator, currentValue) => {
console.log(accumulator, currentValue)
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15 */
/* const arrayOfArrays = [[1, 2], [3, 4], [5, 6]];
// Reducer function to flatten the array
const flattened = arrayOfArrays.reduce((accumulator, currentValue) => {
console.log(accumulator, currentValue)
return accumulator.concat(currentValue);
}, []);
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6] */
const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'banana'];
// Reducer function to count occurrences
const countOccurrences = fruits.reduce((accumulator, currentValue) => {
/* console.log(accumulator,accumulator[currentValue], currentValue) */
if (accumulator[currentValue]) {
accumulator[currentValue]++;
} else {
accumulator[currentValue] = 1;
}
return accumulator;
}, {});
console.log(countOccurrences);
// Output: { apple: 2, banana: 3, orange: 2 }