pullAtIndex - 删除数组中指定索引的值

优质
小牛编辑
133浏览
2023-12-01

改变原始数组,过滤掉指定索引的值。

使用 Array.filter()Array.includes() 来剔除指定的值。使用 Array.length = 0 将数组中的长度重置为零, 并且通过 Array.push() 只使用 pulled 值重新填充数组。使用 Array.push() 来跟踪 pulled 值。

const pullAtIndex = (arr, pullArr) => {
  let removed = [];
  let pulled = arr
    .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
    .filter((v, i) => !pullArr.includes(i));
  arr.length = 0;
  pulled.forEach(v => arr.push(v));
  return removed;
};
let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]