const nums = [1,2,3,3,3,5,5,5]; const chars = ['a','b','a','b','a','a']; const mixed = [1,3,'b',3,'b','a','b',3]; const unique = [1,'a',3]; const distinct = (arr) => arr.filter((el) => arr.filter((item) => item === el).length === 1); console.log(distinct(nums)); // [ 1, 2 ] console.log(distinct(chars)); // [] console.log(distinct(mixed)); // [ 1, 'a' ] console.log(distinct(unique)); // [ 1, 'a', 3 ]
- first, we'll double loop over "arr" with "filter"
arr.filter((el) => arr.filter((item) => ... );
- if "item" is equal to "el" then return its "length"
arr.filter((el) => arr.filter((item) => item === el).length
- this will return the occurrence count for each element in the array
- let' use the 1st example to illustrate this:
- [1,2,3,3,3,5,5,5] --> [1,1,3,3,3,3,3,3]
- 1 occurred 1 time
- 2 occurred 1 time
- 3 occurred 3 time
- 5 occurred 3 time
- to return any element that is non-repeating or unique, we just need to specified length to equal "1"
arr.filter((el) => arr.filter((item) => item === el).length === 1)
- this approach allows you to choose the amount of occurrences from an element you want to return
- for instance, if you you want to return an element that occurs 3 times from an array, then set the "length" to equal 3