i have this site which calculates the sum of values and the thing is in the vals.reduce it adds the first value and then the first value(again) and the second value and then the first(again) and then the second (again) and then the third ...... till the last value, i want it to calculate each value one time so if the values are [1, 2, 3) it returns 6 not 10
const btn = document.getElementById("btn");
const container = document.getElementById("container");
const inps = document.getElementsByClassName("nums");
const sub = document.getElementById("sub");
let box = document.createElement('input');
let vals = [];
let sum;
btn.onclick = () => {
box.setAttribute("type", "number")
box.className = "nums";
container.appendChild(box);
box = document.createElement('input');
}
sub.onclick = () =>{
for(var i=0; i<inps.length; i++){
vals.push(parseInt(inps[i].value));
console.table(vals);
}
let avg = vals.reduce((total, item) => {
isNaN(item) ? item = 0 : console.log("no NaN");
return total + item;
}, 0)
console.log(avg);
}
#container{
user-select: none;
margin: 2.4vh;
display: inline-grid;
grid-template-columns: 1fr 1fr 1fr 1fr ;
gap: .8vh;
}
input{
height: max-content;
width: 15vw;
font-size: xx-large;
}
.btn{
position: sticky;
top: 1vh;
user-select: none;
}
<!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>expermenting</title>
</head>
<body>
<button class="btn" id="btn" >Add number</button>
<button class="btn" id="sub" >Submit numbers</button>
<div id="container">
<input type="number" class="nums">
<input type="number" class="nums">
</div>
<script src="index.js"></script>
</body>
</html>