Sum Array codewars 8kyu
reduce for-of index
by trentHarlem
JavaScript
// use the reduce method to iterate the array for this lovely one liner
// sum=n=>n.reduce((a,c)=>a+c,0)
// Fortunately, the reduce method is available Now! Absolutely free for a limited time only*.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
// or try a jolly little for-of loop
// function sum(numArr) {
// let total = 0;
// for (let digit of numArr)
// total += digit;
// return total
// }
// if you need the index, add the entries method
function sum(numArr) {
let total = 0;
let index = 1,digit=0
// declare both 'index and digit' with let
// -----OR-----
// use var to destructure for function scoped 'index' variable.
//let and const are block scoped and 'index' would not be available outside the for-of loop
// for ( var [index, digit] of numArr.entries()) total += digit;
for ([index, digit] of numArr.entries()) total += digit;
//return total;
//return [total,index]
return `The sum of your ${index+1} digit(s) is ${total}`
}
console.log(sum([5,10,15,20]))