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?

5
  • If you want to performance test various different algorithms in JS, use jsbench.me Commented Oct 6, 2022 at 7:56
  • Thank you for always coming through for me @RoryMcCrossan Commented Oct 6, 2022 at 7:58
  • You can use hashing which will have time complexity O(n). Just create a map and for every element of array, if the current element is present in the map then it is the duplicate else insert the element into the map. Commented Oct 6, 2022 at 7:58
  • Use a Set. Simple and straightforward, no sorting necessary. Commented Oct 6, 2022 at 8:00
  • Would using Set be faster than Sort() Commented Oct 6, 2022 at 8:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.