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]));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map | |
forEach |
Test name | Executions per second |
---|---|
Map | 16178.0 Ops/sec |
forEach | 17488.8 Ops/sec |
Benchmark Explanation
The provided JSON represents two JavaScript microbenchmarks: Map vs forEach
. The benchmark compares the performance of using a Map
data structure versus a traditional forEach
loop to manipulate and transform an array.
Options Compared
Two options are compared:
Map
data structure: This approach uses the Map
object to store unique values as keys, with their corresponding values stored in an array.forEach
loop: This approach iterates over the array using a forEach
loop, pushing each value into its corresponding index in another array.Pros and Cons of Each Approach
Map
data structure and its methods (e.g., has
, get
, set
).Library Used
In this benchmark, no specific library is used. The Map
data structure is a built-in JavaScript object.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes mentioned in the provided code snippets.
Other Alternatives
Alternative approaches to manipulating and transforming arrays could include:
reduce()
methodfilter()
, map()
, or slice()
These alternatives might have different performance characteristics, code readability, and maintainability compared to the Map vs forEach approach.