➡️ Learn more about reduce() method
Here's an example.
<script>
const calculate = () => {
// sum without looping (using reduce method)
const arr = [5, 20, 93, 38, 11].reduce((prev, cur) => prev + cur);
document.write(arr); // Output: 167
}
calculate();
</script>Remember: The "reduce()" method does not change the original array. The elements (or values) remain the same.
Here's a jQuery script that uses $.each() method to get the sum of array values. It loops through each element and returns the sum.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
const calculate = () => {
const arr = [5, 20, 93, 38, 11];
let t = 0;
// sum using a loop (using jQuery each)
$.each(arr, function (index, value) {
t = t + value;
});
document.write (t); // Output: 167
}
calculate();
</script>