Uniq By In JavaScript
uniqBy loops through a given array and makes it unique by checking the returned value. For example, it can be used to find non duplicate entries by the name property:
const cars = [ { name: 'miata', hp: 155, weight: 2400 }, { name: '4c', hp: 237, weight: 2465 }, { name: '4c', hp: 237, weight: 2465 }, { name: 'miata', hp: 155, weight: 2400 }, { name: 'elise', hp: 217, weight: 2000 }, { name: '4c', hp: 237, weight: 2465 }, ]; function uniqBy(arr, callback) { const mapObj = {}; const uniques = []; for (const ele of arr) { const result = callback(ele); if (mapObj[result] !== true) { mapObj[result] = true; uniques.push(ele); } } return uniques; } const uniqueCars = uniqBy(cars, (car) => car.name); console.log(uniqueCars); // [ { name: 'miata', hp: 155, weight: 2400 }, // { name: '4c', hp: 237, weight: 2465 }, // { name: 'elise', hp: 217, weight: 2000 } ]
This is more useful than a map of a single property since now whole objects can be used from that unique list. That uniqBy was just for demonstration purposes though. Most libraries will implement a more complete function. For example, the Lodash uniqBy contains alot of optimizations based on the size of the array and other data characteristics.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2020/uniqBy.js











