Last active
November 24, 2023 19:57
-
-
Save quangnd/572c6d410cb6512b7f252af0f2eb7cae to your computer and use it in GitHub Desktop.
Some examples about reduce() in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Example 1 - Calculate average value of an array (transform array into a single number) | |
var scores = [89, 76, 47, 95] | |
var initialValue = 0 | |
var reducer = function (accumulator, item) { | |
return accumulator + item | |
} | |
var total = scores.reduce(reducer, initialValue) | |
var average = total / scores.length | |
/*Explain about function | |
You'll notice .reduce takes in two values, a callback function and an initial value. | |
The very first time the reducer function is called, it's going to be passed the initialValue you gave it | |
(the 2nd argument to .reduce) and the first item in the actual array. So in our example above the first time | |
that our reducer function runs, accumulator is going to be 0 and item is going to be 89. Remember, the goal | |
is to transform an array into a single value. We currently have two numbers, 0 and 89, and are goal is to get | |
that to one value. Because we're wanting to find the sum of every item in the array, we'll add 89 + 0 to get 89. | |
That brings up a very important step. The thing that gets returned from the reducer function will then be passed | |
as the accumulator the next time the function runs. So when reducer runs again, accumulator will be 89 and item | |
will now be the second item in the array, 76. This pattern continues until we have no more items in the array | |
and we get the summation of all of our reducer functions, which is 307. | |
*/ | |
// ===================== | |
// EXAMPLE 5 - Calculate average | |
function average(arr){ | |
return arr.reduce((a,b)=>a+b)/arr.length | |
} | |
console.log(average([1,2,3,4,5])); //output: 3 | |
// ===================== | |
// EXAMPLE 5 - Count something | |
var arr=[1,2,3,4,5]; | |
//count odd number: | |
console.log(arr.reduce((a,b) => a+(b%2?1:0),0)); //output: 3 | |
//count even number: | |
console.log(arr.reduce((a,b) => a+(b%2?0:1),0)); //output: 2 | |
// ===================== | |
//EXAMPLE 2 - Transform array to an object | |
var votes = [ | |
'tacos', | |
'pizza', | |
'pizza', | |
'tacos', | |
'fries', | |
'ice cream', | |
'ice cream', | |
'pizza' | |
] | |
var initialValue = {} | |
var reducer = function(tally, vote) { | |
if (!tally[vote]) { | |
tally[vote] = 1; | |
} else { | |
tally[vote] = tally[vote] + 1; | |
} | |
return tally; | |
} | |
var result = votes.reduce(reducer, initialValue) // {tacos: 2, pizza: 3, fries: 1, ice cream: 2} | |
// And vice versa (object to array) | |
var maxSpeed = { | |
car:300, | |
bike:60, | |
motorbike:200 | |
} | |
var arr = []; | |
for (var vehicle in maxSpeed) | |
arr.push([vehicle, maxSpeed[vehicle]]) //Output: [["bike", 60], ["motorbike", 200], ["car", 300]] | |
) | |
// =======END=========== | |
// ===================== | |
// EXAMPLE 3 - Counting the occurrences | |
//3.1 Of JavaScript array number elements | |
var newArr = [1,1,3,4,3,2,2] | |
var countObj = newArr.reduce(function (acc, curr) { | |
if (typeof acc[curr] == 'undefined') { | |
acc[curr] = 1; | |
} else { | |
acc[curr] += 1; | |
} | |
return acc; | |
}, {}); | |
//3.2. Count objects that have a specific property: | |
people = [ | |
{name: 'Mary', gender: 'girl'}, | |
{name: 'Paul', gender: 'boy'}, | |
{name: 'John', gender: 'boy'}, | |
{name: 'Lisa', gender: 'girl'}, | |
{name: 'Bill', gender: 'boy'}, | |
{name: 'Maklatura', gender: 'girl'} | |
] | |
var numBoys = people.reduce(function(n, person) { | |
return n + (person.gender == 'boy'); | |
}, 0); | |
//3.3. A function for processing 3.1 & 3.2 | |
var count = function(ary, classifier) { | |
return ary.reduce(function(counter, item) { | |
var p = (classifier || String)(item); | |
counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1; | |
return counter; | |
}, {}) | |
} | |
If you don't provide a classifier this simply counts different elements: | |
> count([1,2,2,2,3,1]) | |
{ | |
"1": 2, | |
"2": 3, | |
"3": 1 | |
} | |
With a classifier you group elements by specific property: | |
> countByGender = count(people, function(item) { return item.gender }) | |
{ | |
"girl": 3, | |
"boy": 3 | |
} | |
Greate ^^ | |
// ====================== |
Great examples. Thanks.
Could you please tell me how to group the array items based on the number passed using the reduce method or any other way?
For ex:
- x=3, arr = [1,2,3,4,5], I need the result to be [[1,2,3], [2,3,4],[3,4,5]]
- x=2, arr = [1,2,3,4,5], I need the result to be [[1,2],[2,3],[3,4],[4,5]]
3 x=1, arr = [1,2,3,4,5], I need the result to be [[1],[2],[3],[4],[5]];
Thanks
Awesome. Thank you.
Very nice!
very helpfull . thanks for sharing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is very much appreciated.