首页 > 解决方案 > 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]

标签: javascript

解决方案


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


推荐阅读