“JavaScript réduit” Réponses codées

JavaScript réduit le tableau d'objets

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

réduire JavaScript

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

Valeurs de tableau de somme 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 réduit

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

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

JavaScript réduit

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 réduit

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

Réponses similaires à “JavaScript réduit”

Questions similaires à “JavaScript réduit”

Plus de réponses similaires à “JavaScript réduit” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code