Skip to content

Commit 879172e

Browse files
Javascript Array Reduce Transformation Day 07
1 parent 148ad5e commit 879172e

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,57 @@
1+
// 2626. Array Reduce Transformation
12

3+
/**
4+
* @param {number[]} nums
5+
* @param {Function} fn
6+
* @param {number} init
7+
* @return {number}
8+
*/
29

10+
// Classic for loop
311

12+
var reduce = function(nums, fn, init) {
13+
let total = init
14+
for(i = 0; i<nums.length; i++){
15+
total = fn(total, nums[i])
16+
}
17+
return total;
418

19+
};
520

621

22+
// for...of with index
723

24+
// var reduce = function(nums, fn, init) {
25+
// let total = init;
26+
// for (let [i, val] of nums.entries()) {
27+
// total = fn(total, val, i);
28+
// }
29+
// return total;
30+
// };
831

932

33+
// forEach
1034

35+
// var reduce = function(nums, fn, init) {
36+
// let total = init;
37+
// nums.forEach((val, i) => {
38+
// total = fn(total, val, i);
39+
// });
40+
// return total;
41+
// };
42+
43+
// recursion
44+
45+
// var reduce = function(nums, fn, init, i = 0) {
46+
// if (i >= nums.length) return init;
47+
// return reduce(nums, fn, fn(init, nums[i], i), i + 1);
48+
// };
49+
50+
51+
// built-in Array.prototype.reduce (meta-solution)
52+
53+
// var reduce = function(nums, fn, init) {
54+
// return nums.reduce((acc, val, i) => fn(acc, val, i), init);
55+
// };
1156

1257

0 commit comments

Comments
 (0)