如何基于指定索引数组移除JavaScript数组中的对应元素?
根据指定索引数组移除数组元素的正确实现方法
问题场景
现有两个数组,需要根据getUniqueRowErrors中的索引值移除data数组对应位置的元素:
const getUniqueRowErrors = [1,3] const data = [ {identifier: '000'}, {identifier: '111'}, {identifier: '222'}, {identifier: '3333'}, {identifier: '444'} ]
期望结果:
const data = [ {identifier: '111'}, {identifier: '3333'}, {identifier: '444'} ]
原代码问题分析
你尝试的代码无法得到正确结果,原因有两点:
map的作用是生成新数组,每个元素是splice返回的被删除元素,而非过滤后的目标数组;splice会直接修改原数组长度,删除前面的索引后,后续索引会发生偏移。比如先删索引1,原数组长度从5变为4,原索引3的元素会变成新索引2,此时再删索引3会误删最后一个元素。
// 错误代码 const filteredData = getUniqueRowErrors.map((rowToRemove) => data.splice(rowToRemove));
正确实现方法
方法一:从后往前删除索引(修改原数组)
将索引数组从大到小排序,从后往前删除元素,避免索引偏移问题:
const getUniqueRowErrors = [1,3]; const data = [ {identifier: '000'}, {identifier: '111'}, {identifier: '222'}, {identifier: '3333'}, {identifier: '444'} ]; // 按索引从大到小排序,再依次删除 getUniqueRowErrors.sort((a, b) => b - a).forEach(index => { data.splice(index, 1); }); console.log(data); // 输出符合预期的结果
方法二:过滤生成新数组(不修改原数组)
使用filter方法,保留索引不在getUniqueRowErrors中的元素,这种方式不会修改原数组,更符合无副作用的编程习惯:
const getUniqueRowErrors = [1,3]; const data = [ {identifier: '000'}, {identifier: '111'}, {identifier: '222'}, {identifier: '3333'}, {identifier: '444'} ]; const filteredData = data.filter((_, index) => !getUniqueRowErrors.includes(index)); console.log(filteredData); // 输出符合预期的结果
方法对比
- 方法一直接修改原数组,适合需要原地修改的场景;
- 方法二返回新数组,原数组保持不变,更安全,适合需要保留原数据的场景。
内容的提问来源于stack exchange,提问作者Raziel
相关产品推荐
相关产品推荐

