“JavaScript reduz” Respostas de código

JavaScript reduz a matriz de objetos

var objs = [
  {name: "Peter", age: 35},
  {name: "John", age: 27},
  {name: "Jake", age: 28}
];

objs.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue.age;
}, 0); // 35 + 27 + 28 = 90
TC5550

Reduza JavaScript

let array = [36, 25, 6, 15];
 
array.reduce((acc, curr) => acc + curr, 0)
// 36 + 25 + 6 + 15 = 82
Rick Oburu

Valores da matriz de soma javascript

function getArraySum(a){
    var total=0;
    for(var i in a) { 
        total += a[i];
    }
    return total;
}

var payChecks = [123,155,134, 205, 105]; 
var weeklyPay= getArraySum(payChecks); //sums up to 722
Grepper

JavaScript reduz

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

array.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0); // 36 + 25 + 6 + 15 = 82
TC5550

JavaScript reduz

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.
Musawir MOSA

JavaScript reduz

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
QuietHumility

Respostas semelhantes a “JavaScript reduz”

Perguntas semelhantes a “JavaScript reduz”

Mais respostas relacionadas para “JavaScript reduz” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código