a soupling
a soupling

Reputation: 3

How do i find the unique number in an array?

I have no idea why this isn't working. The solution was basically the exact opposite of mine, yet that one somehow worked (it examined the first two indexes instead of the last two). Am I missing something?

function findUniq(arr) {
  arr.sort((a, b) => a - b);
  return arr.slice(-2) === arr.pop() ? arr.shift() : arr.pop();
}

console.log(findUniq([0, 1, 0])); // 0, and arr is [0]

Upvotes: 0

Views: 86

Answers (1)

RobG
RobG

Reputation: 147403

Here's what's happening:

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

sorts the array to be:

[0, 0, 1]

In the return expression:

arr.slice(-2) === arr.pop()

resolves as follows:

arr.slice(-2)

returns an array that is a shallow copy of the last two elements of the array. Then

arr.pop()

removes the last element from the array and returns its value, so the array is now [0, 0] and the expression resolves to:

[0, 1] === 1

which is false. Strict comparison of arr.slice(...) to anything will always be false, even arr.slice(-2) === arr.slice(-2) is false as it compares two different objects, although they have the same elements with the same values.

So the false branch of the conditional operator ?: expression is executed:

arr.pop();

resolves to:

[0, 0].pop()

which removes and returns the last element from arr so returns 0 and arr is now [0].

Also see:

  1. MDN: Array.prototype.slice
  2. MDN: Array.prototype.pop

Upvotes: 1

Related Questions