Test name | Executions per second |
---|---|
Map | 16178.0 Ops/sec |
forEach | 17488.8 Ops/sec |
const createLists = (arr = []) => [
arr.reduce((map, val) => {
if (!map.has(val)) {
map.set(val, [val]);
} else {
map.get(val).push(val);
}
return map;
}, new Map()).values()
];
console.log(createLists([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0]));
function createLists(arr = []) {
let authors = [];
let list = [];
arr.forEach(item => {
let authorIndex = authors.includes(item) ? authors.indexOf(item) : (authors.push(item) - 1);
list[authorIndex] = list[authorIndex] || [];
list[authorIndex].push(item);
});
return list;
}
console.log(createLists([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0]));