Skip to content

Commit 309d79b

Browse files
add: solution❤️
1 parent 51ac39c commit 309d79b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Calculate the sum of the numbers in a nested array
2+
3+
You need to calculate the sum of the numbers in an array. However, the array contains nested arrays, whose numbers you must also count. These nested arrays may also have further arrays recursively nested in them, and so on. You do not know how deep the nesting continues. If the list is empty, return zero.
4+
5+
The arrays may also contain data that is not of the type number(`string`, `BigInt`, `object`, etc), which you should ignore.
6+
7+
## Examples
8+
9+
```javascript
10+
nestedSum([1, 2, [3, [4], 5, '6'], 6]); // should == 21
11+
nestedSum([2, [[[[[3]]]]]]); // should == 5
12+
nestedSum([]); // should == 0
13+
```
14+
15+
## Execute
16+
17+
```bash
18+
node solution.js
19+
```
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function nestedSum(arr) {
2+
if (!arr || !Array.isArray(arr)) {
3+
return 0;
4+
}
5+
return arr.flat(Infinity).reduce((prev, value) => prev + (typeof value === 'number' ? value : 0), 0);
6+
}
7+
8+
(() => {
9+
[
10+
undefined,
11+
null,
12+
3,
13+
'abc',
14+
[1, 2, [3, [4], 5, '6'], 6],
15+
[2, [[[[[3]]]]]],
16+
[],
17+
[1, 2, 3],
18+
[1, 2, [4]],
19+
[1, [2, [3], 4], [4, [[1]]]],
20+
[[[[[[[[[[2]]]]]]]]], 3],
21+
].forEach((arr) => {
22+
console.log(JSON.stringify(arr), '==', nestedSum(arr));
23+
});
24+
})();

0 commit comments

Comments
 (0)