SirVeritas SirVeritas - 6 months ago 9
Javascript Question

Return Two-Dimensional Array from Single Dimensional Array in JavaScript

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?

Answer

You need to push xWithSum onto a result array.

var x = ['9493-4937-288383-8473', '4838-38403-8484', '9384-3848-4978-4944', '3920-2108-2845-1904'];
var result = [];
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], sum];
  result.push(xWithSum);
}

console.log(result);

You could also use .map() to run a function on each element of an array and return an array of the results.

var x = ['9493-4937-288383-8473', '4838-38403-8484', '9384-3848-4978-4944', '3920-2108-2845-1904'];
var result = x.map(function(el) {
  var y = el.replace(/[- )(]/g, '');

  var sum = 0;
  var z = y;
  while (z > 0) {
    sum = sum + z % 10;
    z = Math.floor(z / 10);
  }

  var xWithSum = [el, sum];
  return xWithSum;
});

console.log(result);