JavaScript function with loops does not work fast enough

I try to practice an interview and found a call online to write a function that will take an array of numbers and return only those values ​​that exist only once in the array, and return these values ​​in order. For example, the array [1, 3, 5, 6, 1, 4, 3, 6] should return [4, 5].

I have a script that passes tests, but for some tests it runs too slowly. Am I going to do it wrong? Is there any fundamental way to speed this up? the script starts with findTheNumbers, a is the input of the array:

function findTheNumbers(a) {
    var retVal = [];
    var nonUnique = [];

    for (var i = 0; i < a.length; i++){
        var isUnique = true;
        if (i != 0){
            for (var j = 0; j < nonUnique.length; j++){
                if (a[i] == nonUnique[j]){
                    isUnique = false;
                    break;
                }
            }
        }

        if (isUnique){
            for (var k = 0; k < a.length; k++){
                if (a[i] == a[k] && i != k){
                    isUnique = false;
                    nonUnique.push(a[i]);
                    break;
                }
            }    
        }

        if (isUnique){
            retVal.push(a[i]);
            if (retVal.length == 2){
                break;
            }
        }


    }

    retVal = sortArrayOfLengthOfTwo(retVal);
    return retVal;
}

function sortArrayOfLengthOfTwo(array){
    var retVal = [];
    if (array[0] > array[1]){
        retVal.push(array[1]);
        retVal.push(array[0]);
    } else {
        retVal = array;
    }

    return retVal;
}

UPDATE -

I don’t know where this is the best place, but here is my new version based on accepted answer answers (which worked much faster):

function findTheNumbers(a) {
    var retVal = [];
    var dict = {};
    for (var i = 0; i < a.length; i++){
        dict[a[i]] = 1 + (dict[a[i]] || 0);
    }

    for (var key in dict){
        if (dict[key] == 1){
            retVal.push(parseInt(key));
        }
    }

    return retVal;
}
+4
1

,

  • (edit: Bergi)
  • -

n , .. o (n ^ 2). .

. :

  • var, const, let

:

function findTheUniqueNumbers(a) {
  const numberCounts = {} // I prefer "new Map()" on recent env.
  a.forEach( function(e) {
    const previousCount = numberCounts[e] || 0
    numberCounts[e] = previousCount + 1
  } )

  return Object.keys(numberCounts)
    .filter( function(e) {
      return numberCounts[e] === 1
    } )
}


const uniqueNumber = findTheUniqueNumbers([1, 3, 5, 6, 1, 4, 3, 6])
console.log(uniqueNumber)
+5

Source: https://habr.com/ru/post/1672415/


All Articles