Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 16, 2022 08:42 am GMT

JavaScript: Find sum of numbers present in elements of nested array

Hello Dev folks, I'm Gaurav - a front-end focused software developer from India. Recently I came across a JavaScript problem that required me to find sum of all the numbers present in elements of a nested array.
Okay without any further ado, here is the problem:
sum([1, 'x', '2x', ['3', ['x2', '5']]]);

So, you see a nested array with 2 levels of nesting being feed to a sum function.

Immediately it comes to mind that if the array was flattened, the task would have been much easier. So, that's what we are gonna do now. Flatten the array. You can flatten any way you want it -

  1. Use flat method available on arrays.
  2. Use reduce and concat.
  3. Use a library such as lodash.
  4. Use a recursive function

While using flat method on arrays is simplest to implement, I decided go with 4 and write a recursive method to flatten the array. It is fast and works for any input and any level of nesting. I'm using newer ES6 syntax.

const flattenArr = (arr, result = []) => {  for (let i = 0, length = arr.length; i < length; i++) {    const value = arr[i];    if (Array.isArray(value)) {      flattenArr(value, result);    } else {      result.push(value);    }  }  return result;};

Now, we have a flat Array and the task is easier now.
We will use a variable sum to store the result and set its initial value zero.
We can loop through each element of our new Array and if it is a number, we can add and assign it immediately to our sum variable.
The things get exciting when the elements of our new flat array are not a number. You can see in the problem statement above that we have two types of strings, one starting with a number and other starting with a character - '3', '2x' and 'x2'.

For strings, starting with a number, we can directly use parseInt method and it will return the number for first type of string and NaN for the second type of string. That is, after using partseInt on '2x' and '3', we will get 2 and 3 respectively. These values being number can be added to our sum variable. While parseInt('x2') will return NaN.

You can use another inbuilt method isNaN to check if the returned value is NaN. If the value is NaN, then we need to think of other ways to get the number present in that string. Regex comes to our rescue here, we can use a regex to match and filter the number present in string.

const findNumInStringRegex = /\d+/;let findNumInString = num.match(findNumInStringRegex);

This findNumInString will either be null or a number as string i.e, null or '5'.
If it is null there is nothing we can do, but for the other case we can again use parseInt to get the number and add it to our sum variable.

This way, we can add all the numbers present in elements of the nested array given in the problem.
The solution is present in a jsfiddle here.


Original Link: https://dev.to/gauravkrp/javascript-find-sum-of-numbers-present-in-elements-of-nested-array-lbb

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To