如何选择数组中的唯一元素? [英] How can I select a unique element in the array?

查看:147
本文介绍了如何选择数组中的唯一元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决在数组中查找唯一元素的任务. 到目前为止,我设法解决了95%,但是我失败了0.我收到一条错误消息,说应该为0并得到1.

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.

我应该得到//10,但是在在线测试失败之后.对于所有其他值,它都已通过.

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]));

推荐答案

通过使用映射计数每个元素出现的次数,您可以获得一次出现的所有值.然后,您可以将该地图缩小为唯一值数组:

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]))

如果您不关心多个唯一值,则可以对数组进行排序并使用逻辑,而不必检查每个值,前提是该数组仅包含2个不同的值,并且长度大于2:

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]))

这篇关于如何选择数组中的唯一元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆