dlucero dlucero - 1 year ago 64
Javascript Question

How to split array of strings into 2D array of single integers

I am working on an exercise as a very beginner, self-taught (so far) programming student. I was given this array of credit card numbers:

var myArray = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893- 7978', '4556-4242-9283-2260'];

I am to remove the dashes, get the sum of the individual integers of each credit card number, and return the highest sum.

I have removed the dashes correctly:

var myArray = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260'];

var noDashes = myArray.map(function(x){ return x.replace(/-/g,"") });


Next I turned each string into an integer:

var strToInt = noDashes.map(function (x) {
return parseInt(x, 10);



But now I cannot figure out how to iterate over the array and turn each long integer into it's single integers in a 2D array to look like:

var newArray = [[4,9,1,6,2,6,0,0,1,8,0,4,0,5,3,0], [4,7,7,9,2,5,2,8,8,8,3,9,7,2], [4,2,5,2,2,7,8,8,9,3,7,9,7,8], [4,5,5,6,4,2,4,2,9,2,8,3,2,2,6,0]];

I know I need to use a for loop and possibly the .split method but I've been trying for two days with a million different searches and still have not come up with anything that works. I have found the complete answer to this exercise online, but it uses code way too advanced for my understanding, so I've been trying to break up the problem into blocks that I can understand.

I would appreciate some guidance! Thank you!

Answer Source

To get the sum use reduce:

oneArray.reduce(function(a,b) { return a+b })

To apply that to each one, use map:

newArray.map(function(x) { return x.reduce(function(a,b) { return a+b }) })

To get the maximum sum, use Math.max:

Math.max.apply(null, newArray.map(function(x) { return x.reduce(function(a,b) { return a+b }) }))

An extra exercise for you: which card number was it?