I am trying to get the smallest string out of every nested array in the following array object
JavaScript
x
2
1
let data = ["test string", ["abcd", "efj", ["hijklm", ["op"], "hijk", "hijklmn", ["op", "opq"]]]]
2
I have tried the code but it gives me stackoverflow error,Any help please
JavaScript
1
33
33
1
let data = ["test string", ["abcd", "efj", ["hijklm", ["op"], "hijk", "hijklmn", ["op", "opq"]]]]
2
3
let smallest = []
4
5
function getSmallest(data) {
6
7
8
data.forEach((ele, i) => {
9
10
if (typeof ele == "string") {
11
smallest.push(ele);
12
} else if (typeof ele == "object") {
13
// removing the array first
14
let _data = JSON.parse(JSON.stringify(data));
15
let only_array = _data.splice(i, 1);
16
getSmallest(only_array)
17
// now data contains only strings
18
19
//finding the smalles string from array
20
let small = _data.filter(v => typeof v === 'string')
21
.reduce((a, v) => a && a.length <= v.length ? a : v, '')
22
23
smallest.push(small);
24
25
}
26
27
28
});
29
30
31
}
32
getSmallest(data);
33
console.log(smallest)
Required result -Smallest in every array (nested one as well)
JavaScript
1
2
1
["test string", "efj", "hijk", "op", "op"]
2
Advertisement
Answer
You could take a recursive approach.
JavaScript
1
12
12
1
const
2
smallest = array => array
3
.reduce((r, value) => {
4
if (Array.isArray(value)) r.push(smallest(value));
5
else if (!r[0].length || r[0][0].length > value.length) r[0][0] = value;
6
return r;
7
}, [[]])
8
.flat(),
9
data = ["test string", ["abcd", "efj", ["hijklm", ["op"], "hijk", "hijklmn", ["op", "opq"]]]],
10
result = smallest(data);
11
12
console.log(result);