Given an array [1, 2, 3, 4]
, how can I find the sum of its elements? (In this case, the sum would be 10
.)
I thought $.each might be useful,
OK, imagine you have this array below:
const arr = [1, 2, 3, 4];
Let's start looking into many different ways to do it as I couldn't find any comprehensive answer here:
1) Using built-in reduce()
function total(arr) {
if(!Array.isArray(arr)) return;
return arr.reduce((a, v)=>a + v);
}
2) Using for loop
function total(arr) {
if(!Array.isArray(arr)) return;
let totalNumber = 0;
for (let i=0,l=arr.length; i
3) Using while loop
function total(arr) {
if(!Array.isArray(arr)) return;
let totalNumber = 0, i=-1;
while (++i < arr.length) {
totalNumber+=arr[i];
}
return totalNumber;
}
4) Using array forEach
function total(arr) {
if(!Array.isArray(arr)) return;
let sum=0;
arr.forEach(each => {
sum+=each;
});
return sum;
};
and call it like this:
total(arr); //return 10
It's not recommended to prototype something like this to Array...