Answers for "rarray reduce"

90

javascript reduce

var array = [36, 25, 6, 15];

array.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0); // 36 + 25 + 6 + 15 = 82
Posted by: Guest on May-21-2020
8

reduce javascript

var depthArray = [1, 2, [3, 4], 5, 6, [7, 8, 9]];

depthArray.reduce(function(flatOutput, depthItem) {
    return flatOutput.concat(depthItem);
}, []);

=> [1, 2, 3, 4, 5, 6, 7, 8, 9];


// --------------
const prices = [100, 200, 300, 400, 500];
const total = prices.reduce((total, cur) => {return total + cur} )
//  init value = 0 => total = 1500;


// --------------
const prices = [100, 200, 300, 400, 500];
const total = prices.reduce(function (total, cur) => {
                   return total + cur
                }, 1 )
// init value = 1 => so when plus all numnber will be result => 1501;

// --------------
const prices = [100, 200, 300, 400, 500];
const total = prices.reduce((total, cur) => total + cur )
// 1500;
Posted by: Guest on March-03-2022
0

javascript reduce

You can return whatever you want from reduce method, reduce array method good for computational problems
const arr = [36, 25, 6, 15];
array.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0); // this will return Number
array.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, []); // this will return array
let {total} = array.reduce(function(accumulator, currentValue) {
  let {currentVal} = currentValue
  return accumulator + currentVal;
}, {
total: 0
}); // this will return object
And one additional rule is always always retrun the first param, which do arithmetic operations.
Posted by: Guest on January-13-2022
5

reduce javascript

//note idx and sourceArray are optional
const sum = array.reduce((accumulator, element[, idx[, sourceArray]]) => {
	//arbitrary example of why idx might be needed
	return accumulator + idx * 2 + element 
}, 0);
Posted by: Guest on April-26-2020
0

javascript reduce

let arr = [1,2,3]

/*
reduce takes in a callback function, which takes in an accumulator
and a currentValue.

accumulator = return value of the previous iteration
currentValue = current value in the array

*/

// So for example, this would return the total sum:

const totalSum = arr.reduce(function(accumulator, currentVal) {
	return accumulator + currentVal
}, 0);

> totalSum == 0 + 1 + 2 + 3 == 6

/* 
The '0' after the callback is the starting value of whatever is being 
accumulated, if omitted it will default to whatever the first value in 
the array is, i.e: 

> totalSum == 1 + 2 + 3 == 6

if the starting value was set to -1 for ex, the totalSum would be:
> totalSum == -1 + 1 + 2 + 3 == 5
*/


// arr.reduceRight does the same thing, just from right to left
Posted by: Guest on January-25-2022

Code answers related to "Javascript"

Browse Popular Code Answers by Language