0

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?

  • Step 1: [`flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat). Step 2: https://stackoverflow.com/a/840808/519413 – Rory McCrossan Oct 05 '22 at 16:16
  • I don't want to debug it. I want an entirely new function. Created by someone here – Joseph Etim Oct 05 '22 at 16:18
  • 1
    That's not how this site works. We are here to help you to debug code, not to write it for you. – Rory McCrossan Oct 05 '22 at 16:21
  • Oh, I would actually drop the one I did. Thanks for the Information. – Joseph Etim Oct 05 '22 at 16:33
  • As for the links you dropped, that gave me a very good idea. By flattening the array and looking for the duplicates. But the [link](http://stackoverflow.com/a/840808/519413) , the function there breaks with repeated values of more than 2. Thank you for your efforts @RoryMcCrossan – Joseph Etim Oct 05 '22 at 16:37

0 Answers0