// 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));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
original duplicate removal | |
2-pass approach |
Test name | Executions per second |
---|---|
original duplicate removal | 167509.2 Ops/sec |
2-pass approach | 254184.1 Ops/sec |
Measuring the performance of JavaScript microbenchmarks is crucial to optimize code execution and identify bottlenecks.
Benchmark Overview
The provided benchmark measures the performance of two approaches to remove duplicates from an array that occur 3 or more times:
Options Compared
Both approaches have their pros and cons:
Library and Special JS Feature
In this benchmark, there is no specific library or special JavaScript feature being tested. However, the 2-pass approach uses a common JavaScript technique called "mapping" or "counting," which is used to iterate through an array and perform calculations based on each element's value.
Alternative Approaches
Other possible approaches to remove duplicates from an array include:
Set
data structure (e.g., [...new Set(numbers)]
)for...of
loop with a reduce()
methodKeep in mind that each approach has its own trade-offs, and the best choice will depend on the specific requirements of your use case.