I am trying to get the smallest string out of every nested array in the following array object
let data = ["test string", ["abcd", "efj", ["hijklm", ["op"], "hijk", "hijklmn", ["op", "opq"]]]]
I have tried the code but it gives me stackoverflow error,Any help please
let data = ["test string", ["abcd", "efj", ["hijklm", ["op"], "hijk", "hijklmn", ["op", "opq"]]]] let smallest = [] function getSmallest(data) { data.forEach((ele, i) => { if (typeof ele == "string") { smallest.push(ele); } else if (typeof ele == "object") { // removing the array first let _data = JSON.parse(JSON.stringify(data)); let only_array = _data.splice(i, 1); getSmallest(only_array) // now data contains only strings //finding the smalles string from array let small = _data.filter(v => typeof v === 'string') .reduce((a, v) => a && a.length <= v.length ? a : v, '') smallest.push(small); } }); } getSmallest(data); console.log(smallest)
Required result -Smallest in every array (nested one as well)
["test string", "efj", "hijk", "op", "op"]
Advertisement
Answer
You could take a recursive approach.
const smallest = array => array .reduce((r, value) => { if (Array.isArray(value)) r.push(...smallest(value)); else if (!r[0].length || r[0][0].length > value.length) r[0][0] = value; return r; }, [[]]) .flat(), data = ["test string", ["abcd", "efj", ["hijklm", ["op"], "hijk", "hijklmn", ["op", "opq"]]]], result = smallest(data); console.log(result);