Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Last active April 24, 2020 05:53
Show Gist options
  • Save mojaray2k/f3ffbfabddc9389770ee2cd0c9232426 to your computer and use it in GitHub Desktop.
Save mojaray2k/f3ffbfabddc9389770ee2cd0c9232426 to your computer and use it in GitHub Desktop.
Using Array Reduce

Definition and Usage

The reduce() method reduces the array to a single value.

The reduce() method executes a provided function for each value of the array (from left-to-right).

The return value of the function is stored in an accumulator (result/total).

Note: reduce() does not execute the function for array elements without values.

Note: this method does not change the original array.

// Subtract the numbers in the array, starting from the beginning:
var numbers = [175, 50, 25];

function myFunc(total, num) {
  return total - num;
}

console.log(numbers.reduce(myFunc));
console.log(numbers); // Reduce does not change the array

// Round all the numbers in an array, and display the sum:
var numbers = [15.5, 2.3, 1.1, 4.7];

function getSum(total, num) {
  return total + Math.round(num);
}

console.log(numbers.reduce(getSum));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment