拼接是最快的方法
const array = [0, 1, 2, 3, 4, 5];
const indicesToRemove = [0, 2, 5];
for (let index = indicesToRemove.length; index >= 0 ; index--) {
array.splice(index, 1);
}
如果你处理大量数据并创建新的数组,例如filter或push,你将遇到内存问题。
基准测试:
const array1 = [...new Array(5000).keys()];
const indicesToRemove1 = [...new Array(5000).keys()];
const array2 = [...new Array(5000).keys()];
const indicesToRemove2 = [...new Array(5000).keys()];
const array3 = [...new Array(5000).keys()];
const indicesToRemove3 = [...new Array(5000).keys()];
const array4 = [...new Array(5000).keys()];
const indicesToRemove4 = new Set([...new Array(5000).keys()]);
测试1
for (let index = indicesToRemove1.length; index >= 0 ; index--) {
array1.splice(index, 1);
}
测试2
for (let index = indicesToRemove2.length; index--;) {
array2.splice(index, 1);
}
测试 3
const newArray = array4.filter((_,i) => !indicesToRemove4.has(i))
// 3,322 ops/s ±0.5%
// 2.25% slower
测试4
const newArray = array3.filter((_,i) => !indicesToRemove3.includes(i))
// 22 ops/s ±5.6%
// 99.35% slower