“JavaScript reduzieren” Code-Antworten

JavaScript reduzieren Array von Objekten

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

JavaScript reduzieren

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

JavaScript -Summen -Array -Werte

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 reduzieren

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

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

JavaScript reduzieren

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 reduzieren

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

Ähnliche Antworten wie “JavaScript reduzieren”

Fragen ähnlich wie “JavaScript reduzieren”

Weitere verwandte Antworten zu “JavaScript reduzieren” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen