GOAL: add all elements from an array of integers and arrays, each child array is a set of 2 integers denoting a start and end of a range.
HTML invocation:
JavaScript
x
3
1
<div class="block" onclick="test([33,88,[1,5],[8,13],[22,25]]);">click</div>
2
<div id="paper"></div>
3
I have the following JavaScript:
JavaScript
1
28
28
1
<script>
2
function test(clickArray) {
3
let theArray = [];
4
for (i = 0; i < clickArray.length; i++) {
5
theArray.push(clickArray[i]);
6
if (clickArray[i].length > 1) {
7
range(clickArray[i][0], clickArray[i][1], theArray);
8
}
9
}
10
writeArray(theArray);
11
}
12
13
function writeArray(anArray) {
14
let pencilArray = [];
15
for (let i = 0; i < anArray.length; i++) {
16
pencilArray.push();
17
}
18
document.getElementById("paper").innerHTML = pencilArray.join("<br>");
19
}
20
21
function range(start, end, rangeArray) {
22
for (let i = start; i <= end; i++) {
23
rangeArray.push(i);
24
}
25
return rangeArray;
26
}
27
</script>
28
When I invoke the onclick JavaScript the output is:
JavaScript
1
21
21
1
33
2
88
3
1,5
4
1
5
2
6
3
7
4
8
5
9
8,13
10
8
11
9
12
10
13
11
14
12
15
13
16
22,25
17
22
18
23
19
24
20
25
21
Both the range passed and the elements constructed by the range() function are added to the final array, but I just want the elements, not the ranges, so output should be:
JavaScript
1
18
18
1
33
2
88
3
1
4
2
5
3
6
4
7
5
8
8
9
9
10
10
11
11
12
12
13
13
14
22
15
23
16
24
17
25
18
Advertisement
Answer
Here’s how you can handle numbers along with ranges.
JavaScript
1
15
15
1
const test = (arr) => {
2
const allNumbers = arr.reduce((acc, el) => {
3
if (Array.isArray(el)) {
4
const [start, end] = el;
5
for (let i = start; i <= end; i++) {
6
acc.push(i)
7
}
8
} else if (!Number.isNaN(el)) {
9
acc.push(el)
10
}
11
return acc
12
}, [])
13
14
document.getElementById('paper').innerHTML = allNumbers.join('<br />');
15
}
JavaScript
1
2
1
<div class="block" onclick="test([[1,5],[8,13],[22,25], 99]);">click</div>
2
<div id="paper"></div>