// Remove duplicates that occur 3 or more times in an array
// keeping unique values and those with less than 3
function removeMany(arr) {
const newArr = Array.from(arr).sort()
let count = 0;
let result = []
newArr.forEach((value, index, ar) => {
count += 1;
// refactored afterwards from (ar[index + 1] !== value)
if (ar.lastIndexOf(value) <= index && count <= 2) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
result.push(arr[i])
}
}
count = 0
} else if (ar[index + 1] !== value) {
count = 0;
}
});
// +1 is there anyway to return a result that mimicks the original order of `numbers`?
return result; // [1, 2, 2, 3, 4, 4]
}
const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
console.log(removeMany(numbers));
// Remove duplicates that occur 3 or more times in an array
// keeping unique values and those with less than 3
function removeMany(arr) {
let countMappings = arr.reduce(function(carry, item) {
if (carry[item]!== undefined) {
carry[item]++;
}
else {
carry[item] = 1;
}
return carry;
}, {});
return arr.reduce(function(final, item) {
if (countMappings[item] <3) {
final.push(item);
}
return final;
}, []);
}
const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
console.log(removeMany(numbers));
function removeMany(numbers, max) {
const numberMap = numbers.reduce((map, num) => {
map[num] = map[num] ? map[num] + 1 : 1;
return map;
}, []);
return numbers.filter(num => numberMap[num] < max);
}
const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
console.log(removeMany(numbers));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
original duplicate removal | |
2-pass approach | |
filtering |
Test name | Executions per second |
---|---|
original duplicate removal | 35122.6 Ops/sec |
2-pass approach | 37007.1 Ops/sec |
filtering | 59029.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested in this benchmark.
Benchmark Definition
The benchmark is designed to measure the performance of removing duplicates from an array, where duplicates exceed a certain threshold (N). The goal is to keep unique values and those with less than N occurrences.
Test Cases
There are three test cases:
filter()
method to directly filter out elements with more than N occurrences.Options Compared
These three approaches are compared in terms of their performance and efficiency.
Pros and Cons
Here's a brief summary of each approach:
Other Considerations
When choosing an approach, consider the trade-offs between performance, readability, and maintainability. If you prioritize speed above all else, the filtering approach might be the best choice. However, if you need to implement this functionality in a production environment, the 2-pass approach or brute force approach might be more suitable due to their ease of understanding.
Libraries and Special Features