🤨 What Random

Finding unique values in a Javascript Array using Object.fromEntries

Javascript objects act as dictionaries. They can't hold duplicate keys. I think we can turn it into an advantage if we want to find the unique values in an Array.

const arr = ["foo", "bar", "baz", "foo"];

const uniq = (arry) => 
    	arr.reduce((obj, key) => Object.assign({}, obj, { [key]: null })

uniq(arr) // ["foo", "bar", "baz"]

Understandably, this only works for primitive values that can be represented as key keys in a Javascript object.

If you want to compare non-primitive values like functions, objects, and arrays, you can however JSON.stringify the value.

#programming #javascript

- 1 toast