1

I am writing a javascript function that takes a nested array and returns the numbers that occurs more than once in that array. I believe my function is accurate (meaning that it passes their "Correctness test" ) but i am after efficiency, how efficient is this code?

For example - Lets call the name of the function deepSort(nestedArray) where nestedArray is the nested array parameter

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()
}

const a = deepSort([[1,3,4,5], [4,7,9,1,3], [2,3,5], [1,2,3,4]]) // Returns 1,2,3,4,5
console.log(a);

const b = deepSort([[1,2,3], [4,5], [6,7,8], [2,9,0]]) // Returns 2
console.log(b);

const c = deepSort([[2,7,9], [4,3], [9,6,5], [1,4,3]]) // Returns 3,4,9
console.log(c);

Can this code be optimized any more for speed and efficiency when handling extremely large values of data?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

0 Answers0