Naive unique array - different ways
Improvements needed: take an isEqual function as a parameter to get more control
by jonahe
JavaScript
const samples = ["one", "two", "three", "one", "four", "two", "five"];
const getUniqueWithFilter = (samples) => {
return samples.filter((samp, index, all) => {
const identicalInstances = all.filter(s => s === samp);
if(identicalInstances.length >= 2) {
const firstMatchIndex = all.findIndex(x => x === samp);
return firstMatchIndex === index;
}
return true;
})
};
console.log("filter", getUniqueWithFilter(samples));
const getUniqueWithReduce = (samples) => {
return samples.reduce((soFar, next) => {
if(soFar.find(x => x === next) !== undefined) return soFar;
else return soFar.concat(next);
}, []);
}
console.log("reduce", getUniqueWithReduce(samples))
console.log("set", Array.from(new Set(samples)))