javascript - How do I get the numbers that do not have a duplicated value in an array of numbers?
问题描述
Is there a way to filter an array so that only the unique (distinct) items are left? (not to be confused with removing duplicated items)
I'm looking for something like this:
arrayDistinct([1, 2, 1, 3, 2, 4])
//=> [3, 4]
解决方案
For enhanced performance, you can first iterate over the array once to create an object representing the frequency of each element and then filter the array to get all the elements with a frequency of 1
. This solution runs in O(n)
time and space.
const arrayDistinct = arr => {
const freq = arr.reduce((acc,curr)=>(acc[curr]=(acc[curr]||0)+1,acc), {});
return arr.filter(x => freq[x] === 1);
}
console.log(arrayDistinct([1, 2, 1, 3, 2, 4]));
For arrays that contain elements of different types that have the same string representation, we can use a Map
instead of an object to store frequency.
const arrayDistinct = arr => {
const freq = arr.reduce((map,curr)=>(map.set(curr, (map.get(curr)||0)+1),map), new Map);
return arr.filter(x => freq.get(x) === 1);
}
console.log(arrayDistinct([1, 2, 1, 3, 2, 4, '1']));
推荐阅读
- html - 响应式 iframe 视频列表居中水平和最大宽度
- c# - UWP 包括媒体播放器传输栏作为命令栏的一部分?
- php - PHP get_headers() 生成头文件
- java - 在 Java 进程上调用 Windows10 计算器?
- java - 如果我知道导入级别路径,如何找到要放入库的 pom.xml 的工件 ID
- android - Android Studio 中未列出的 API 级别
- mongodb - MongoDB缓存聚合阶段
- c# - EF Core 不必要地执行条件赋值逻辑的两个分支
- google-api - Google 云端硬盘版本历史记录 - 谁是“已删除用户”?
- ruby-on-rails - 是什么导致模型错误 - 参数数量错误(给定 2,预期 0..1)?