Search code examples
javascriptarrayssortinguniqueelement

How can I select a unique element in the array?


I'm trying to solve this task of finding the unique element inside an array. So far I managed to solve 95%, but I'm failing on 0. I get an error saying that expected 0 and got 1.

I should get //10, which it does, but after I'm failing the test online. For all other values it has passed.

Any ideas about how to solve this and what I'm missing here?

function findOne(arr) {
  let x = arr[0];
  for (let i of arr) {
    if (i === x) {
      continue;
    } else {
      x = i;
    }
    return x;
  }
}
console.log(findOne([3, 10, 3, 3, 3]));


Solution

  • You can get all values that appear once, by using a map to count how many times each element has appeared. You can then reduce that map into an array of unique values:

    const findUnique = arr => {
      const mapEntries = [...arr.reduce((a, v) => a.set(v, (a.get(v) || 0) + 1), new Map()).entries()]
      return mapEntries.reduce((a, v) => (v[1] === 1 && a.push(v[0]), a), [])
    }
    
    console.log(findUnique([3, 10, 3, 3, 3]))
    console.log(findUnique([1, 2, 3, 2, 4]))
    console.log(findUnique([4, 10, 4, 5, 3]))

    If you don't care about multiple unique values, you can just sort the array and use logic, rather than checking every value, provided the array only contains 2 different values, and has a length greater than 2:

    const findUnique = arr => {
      a = arr.sort((a, b) => a - b)
      if (arr.length < 3 || new Set(a).size === 1) return null
      return a[0] === a[1] ? a[a.length-1] : a[0]
    }
    
    console.log(findUnique([3, 10, 3, 3, 3]))
    console.log(findUnique([3, 3, 1]))
    console.log(findUnique([3, 1]))
    console.log(findUnique([3, 3, 3, 3, 3]))