DEV Community

John Peters
John Peters

Posted on

Reducing An Array of Strings to a Single Integer

let nums = ["333","44","5555"];
let singleNum = nums.reduce((acc,item)=>acc+=item);
// convert "333445555"
let finalNumber = Number.parseInt(singleNum);
// outcome
333445555
Enter fullscreen mode Exit fullscreen mode

Note this only works when the input array is a string representation of numbers, easily handled by regex validation.

The nicety of the reduce function allows us to iterate through each item in the array and using the accumulator, we concatenate each item. From there we use the built-in string to integer function found in the Number object. Voila!

JWP2020 Array to Integer conversion

Top comments (0)