Here is one potential solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum an Array of Numbers</title>
</head>
<body>
<script>
let numbers = [4, 10, 5, 7, 13, 20];
let total = numbers.reduce((total, current) => total + current, 0);
console.log(`Sum of array values is ${total}`);
</script>
</body>
</html>
I recorded a video as well that walks through a few other solutions that could work:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum an Array of Numbers</title>
</head>
<body>
<script>
let numbers = [4, 10, 5, 7, 13, 20];
let sum = 0
numbers.forEach(num => sum += num)
console.log(sum)
</script>
</body>
</html>
Hi @anilcha - welcome to the forums! Really nicely done with your entry. Very compact too
You got the badge for completing this!
Cheers,
Kirupa
I’m going to take advantage of the DOM to do the adding for me!
let numbers = [4, 10, 5, 7, 13, 20];
function div (width) {
let el = document.createElement("div");
el.style.display = 'inline-block';
if (width) el.style.width = `${width}px`;
return el;
}
let container = document.body.appendChild(div());
numbers.forEach(num => container.appendChild(div(num)));
let total = container.offsetWidth;
container.remove();
console.log(`Sum of array values is ${total}`);
Thank you.
[4, 10, 5, 7, 13, 20].reduce(0, +) // Swift
I’ve often wished JS had an add function, something along the lines of Math.max but for adding. The you’d be able to do something like
Math.add(...numbers)
Why not:
Math.prototype.add = function(…nums){let acc = 0; for(let num of nums){acc += num} return acc}
even if they did release a Math.add
It would probably be the same…
Steve, Sen - you both got the badge (in case you didn’t get it already!)
Can I use R?
numbers = c(4, 10, 5, 7, 13, 20)
sum(numbers)
Yes! That is awesome
My word, I just discovered all of the other challenges. I’m going to be busy for a while.
The evil way
let numbers = [4, 10, 5, 7, 13, 20];
eval(numbers.join(‘+’));
That is pure evil! But, it does earn you a badge