Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active October 13, 2023 01:40
Show Gist options
  • Select an option

  • Save lewdev/32942772b4df95138e434d3376ac3bb1 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/32942772b4df95138e434d3376ac3bb1 to your computer and use it in GitHub Desktop.
πŸ‘¨β€πŸ’» Three Implementations of `lodash` `_.uniq` (shortest being 22 chars)

πŸ‘¨β€πŸ’» Three Implementations of lodash _.uniq

I was writing tiny code and attempted to get all unique values of an array.

I totally forgot the best implementation, but I thought my first 2 implementations use some interesting code golfing techniques.

The html file demonstrates its uses on an array of primitive values.

πŸ‘‰ Method 1 (46b): find its duplicate in an array and add or not using the reduce method

a.reduce((p,o)=>p.find(q=>q==o)?p:[...p,o],[])

This is the least efficient and longest implementation, but I used the spread operator to add each element.

πŸ‘‰ Method 2 (43b): Using an Object {}, set each value to its attribute and then get its Object.keys.

Object.keys(a.reduce((p,o)=>(p[o]=1,p),{}))

πŸ‘‰ Method 3 (22b): Using the Set Global Object and it will convert the array into its unique values

The Array.from method turns the object into an array.

Array.from(new Set(a))

This is probably the most efficient since it's a Global Object built into the browser.

<p id=o></p>
<script>
const method1 = a => a.reduce((p,o)=>p.find(q=>q==o)?p:[...p,o],[])
const method2 = a => Object.keys(a.reduce((p,o)=>(p[o]=1,p),{}))
const method3 = a => Array.from(new Set(a))
const test = (method, a) => `${method.name}=${method(a)}
| ${method.toString().length - 5} chars`; //we subtract 5 to negate the `a => ` part of the implementation
const a = [1,2,3,4,5,5,5,5,7,7,7,7];
o.innerHTML = [
test(method1, a),
test(method2, a),
test(method3, a),
].join`<br><br>`
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment