I know how to do this combining a lot of if...else
statements but I need a faster and more efficient way.
I need a function that will run through a nested array and return the numbers that occur more than once in the nested array.
this doesn't work with nested arrays and even if you use flat()
, the code still breaks when the duplicates in the array are more than 2
For example-
Lets call the name of the function deepSort(nestedArray)
where nestedArray
is the nested array parameter
deepSort([[1,3,4,5], [4,7,9,1,3], [2,3,5], [1,2,3,4]]) //Returns 1,2,3,4,5
deepSort([[1,2,3], [4,5], [6,7,8], [2,9,0]]) //Returns 2
deepSort([[2,7,9], [4,3], [9,6,5], [1,4,3]]) //Returns 3,4,9
What I tried
function deepSort(nestedArray) {
const flatArr = nestedArray.flat().sort();
let results = []
for (let i = 0; i < flatArr.length - 1; i++) {
if (flatArr[i + 1] ==flatArr[i]) {
results.push(flatArr[i]);
}
}
return (results.filter((item,index) => results.indexOf(item) === index)).join()
}
Can this be optimized any more for speed and efficiency when handling larger values of data?