I have a single dimension array of a series of numbers:
var x = ['9493-4937-288383-8473', '4838-38403-8484', '9384-3848-4978-4944', '3920-2108-2845-1904'];
I'm trying to insert the sum of the digits of each number alongside it to create a two-dimensional array, so that the output is:
[ [ '9493-4937-288383-8473', 96 ],
[ '4838-38403-8484', 65 ],
[ '9384-3848-4978-4944', 96 ],
[ '3920-2108-2845-1904', 58 ] ]
Unfortunately, my code:
for (var i = 0; i < x.length; i ++) {
var y = x[i].replace(/[- )(]/g,'');
var sum = 0;
var z = y;
while (z > 0) {
sum = sum + z % 10;
z = Math.floor(z / 10);
}
var xWithSum = [x[i]];
xWithSum.push(sum);
console.log(xWithSum);
}
results in the following output instead:
[ '9493-4937-288383-8473', 96 ]
[ '4838-38403-8484', 65 ]
[ '9384-3848-4978-4944', 96 ]
[ '3920-2108-2845-1904', 58 ]
That is, I'm ending up with four separate two-dimensional arrays rather than one two-dimensional array with four items.
Will someone please show me the error of my (newbie) JavaScript ways?