It is quite common to use Set
to remove duplicate items from an array. This can be achieved by wrapping an existing array into Set
constructor and then transforming it back into array:
const arr = [1, 2, 'a', 'b', 2, 'a', 3, 4];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, "a", "b", 3, 4]
This works great for arrays of primitive values, however when applying the same approach to array of arrays or objects, the result is quite disappointing:
const arr = [[1, 2], {'a': 'b'}, {'a':2}, {'a':'b'}, [3, 4], [1, 2]];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [[1, 2], {'a': 'b'}, {'a':2}, {'a':'b'}, [3, 4], [1, 2]]
This is because Set
compares non-primitive values by reference and not by value, and in our case all values in array have different reference.
#web-development #maps #javascript-tips #javascript #react