Public
Edited
Apr 26, 2023
Importers
5 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
uniqueWhile = (arr, fn) => {
let out = [],
i = -1,
n = arr.length;
while (++i < n){
const d = fn ? fn(arr[i], i, arr) : arr[i];
if (!out.includes(d)) out.push(d);
}
return out;
}
Insert cell
uniqueWhileTest = test(uniqueWhile)
Insert cell
Insert cell
uniqueFor = (arr, fn) => {
let out = [];
for (let i = 0, n = arr.length; i < n; i++){
const d = fn ? fn(arr[i], i, arr) : arr[i];
if (!out.includes(d)) out.push(d);
}
return out;
}
Insert cell
uniqueForTest = test(uniqueFor)
Insert cell
Insert cell
uniqueForOf = (arr, fn) => {
let out = [],
i = 0;
for (let value of arr){
const d = fn ? fn(value, i, arr) : value;
if (!out.includes(d)) out.push(d);
i++;
}
return out;
}
Insert cell
uniqueForOfTest = test(uniqueForOf)
Insert cell
Insert cell
uniqueSet = (arr, fn) => {
return [...new Set(fn ? arr.map(fn) : arr)];
}
Insert cell
uniqueSetTest = test(uniqueSet)
Insert cell
Insert cell
uniqueReduce = (arr, fn) => {
let i = 0;
return arr.reduce((a, d) => {
const dx = fn ? fn(d, i , arr) : d;
if (!a.includes(dx)) { a.push(dx); }
i++;
return a;
}, []);
}
Insert cell
uniqueReduceTest = test(uniqueReduce)
Insert cell
Insert cell
uniqueForEach = (arr, fn) => {
let out = [];
arr.forEach((d, i) => {
const dx = fn ? fn(d, i, arr) : d;
if (!out.includes(dx)) out.push(dx);
});
return out;
}
Insert cell
uniqueForEachTest = test(uniqueFor)
Insert cell
Insert cell
uniqueD3Union = (arr, fn) => Array.from(fn ? d3.union(arr.map(fn)) : d3.union(arr))
Insert cell
uniqueD3UnionTest = test(uniqueD3Union)
Insert cell
Insert cell
uniqueD3Groups = (arr, fn) => d3.groups(fn ? d3.groups(arr, fn) : d3.groups(arr, d => d)).map(d => d[0])
Insert cell
uniqueD3GroupsTest = test(uniqueD3Groups)
Insert cell
Insert cell
array = Array.from({length: 1e7}, (d, i) => i % 10).map(d => ({value: d}));
Insert cell
test = fn => {
let time = new Date().getTime();
const result = fn(array, d => d.value);
return {time: new Date().getTime() - time, result};
}
Insert cell
result = [
{
f: "while",
t: uniqueWhileTest.time
},
{
f: "for",
t: uniqueForTest.time
},
{
f: "for...of",
t: uniqueForOfTest.time
},
{
f: "Set",
t: uniqueSetTest.time
},
{
f: "Array.reduce",
t: uniqueReduceTest.time
},
{
f: "Array.forEach",
t: uniqueForEachTest.time
},
{
f: "d3.union",
t: uniqueD3UnionTest.time
},
{
f: "d3.groups",
t: uniqueD3GroupsTest.time
}
]
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more