-1

function solution(statues) {
  statues.sort()
  let fullArray = [];
  let missingStatues = [];
  for (let i = Math.min(...statues); i <= Math.max(...statues); i++) {
    fullArray.push(i);
  }
  for (let i = 0; i < fullArray.length; i++) {
    if (!(fullArray[i] in statues)) {
      missingStatues.push(fullArray[i]);
    }
  }
  let missingStatuesCount = missingStatues.length;
  return missingStatues;
}

console.log(solution([6, 2, 3, 8]))

I was expecting [4, 5, 7] but I got [4, 5, 6, 7, 8]. The loop that pushes fullArray[i] into missingStatues, is also pushing [6] and [8], which are in statues and should not be pushed.

depperm
  • 10,606
  • 4
  • 43
  • 67
  • 6
    You have misunderstood what the `in` operator does. – Pointy Mar 24 '22 at 13:54
  • 4
    As Pointy mentioned, you're probably looking for [`includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes): `if (!statues.includes(fullArray[i]))` – 0stone0 Mar 24 '22 at 13:55
  • Does this answers your question? [How do you check if a variable is an array in JavaScript?](https://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript) – 0stone0 Mar 24 '22 at 13:56

1 Answers1

1
function solution(statues) {
    statues.sort()

The default comparisons made by the .sort() method are string comparisons. Your arrays contain numbers, apparently, so you need a numeric comparator function:

    statues.sort((a, b) => a - b);

Then:

    for (let i=Math.min(...statues);i<=Math.max(...statues);i++) {
        fullArray.push(i);
    }

Once you have successfully sorted the array, statues[0] will be the smallest value and statues[statues.length - 1] will be the largest. There is no need to copy the array and call Math.min() or Math.max().

    for (let i=0;i<fullArray.length;i++) {
        if (!(fullArray[i] in statues)) {
            missingStatues.push(fullArray[i]);
        } 
    }

The in operator is for checking object keys, not values. What you're looking for is the .includes() method:

        if (!statues.includes(fullArray[i]))
Pointy
  • 405,095
  • 59
  • 585
  • 614