获取不包含某个索引元素的数组

9

我实现了一个函数,可以获取一个数组的浅拷贝,并删除其中的某个元素(使用其索引)。

但是,我需要调用三个方法才能完成此操作。有没有更好的方法来实现这个功能?

const arrayWithoutElementAtIndex = function (arr, index) {
    return arr.slice(0, index).concat(arr.slice(index + 1))
}

arrayWithoutElementAtIndex([1, 2, 4, 8, 16, 32, 64], 3) // [1, 2, 4, 16, 32, 64]
3个回答

19

那么一个常规的filter怎么样?

const arrayWithoutElementAtIndex = function (arr, index) {
  return arr.filter(function(value, arrIndex) {
    return index !== arrIndex;
  });
}
document.write(arrayWithoutElementAtIndex([1, 2, 4, 8, 16, 32, 64], 3)); // [1, 2, 4, 16, 32, 64]

这意味着你只有一个函数,它返回一个新的数组实例。


啊耶!筛选器...... 傻瓜!我希望ES6实现了非"fat arrow notation",或者至少提供了一个 fn 关键字。到处写 function 让一行代码难以在80个字符内完成。 - user1534422
1
@user1534422,你可以这样做:const arrayWithoutElementAtIndex = (arr, index, newArr = [...arr]) => (newArr.splice(index,1), newArr),你可以看到我的答案编辑。请原谅我的英语。 - Walter Chapilliquen - wZVanG
1
代码高尔夫:const filter = (arr, index) => arr.filter((_, i) => index !== i); - Marc

0

使用 lodash:

_(this.state.additionalOwners, index).splice(index, 1).value())

0

你可以使用splice()进行两个操作,但是看起来不太好

'use strict'

const arrayWithoutElementAtIndex = function(arr, index) {
  var ret = arr.slice(); //make a copy
  ret.splice(index, 1); //remove the item from given index
  return ret; //return the copy
}

var array = [1, 2, 4, 8, 16, 32, 64];
var array2 = arrayWithoutElementAtIndex(array, 3) // [1, 2, 4, 16, 32, 64]

snippet.log(array)
snippet.log(array2)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


是的,我试图避免使用splice,因为最终代码行数会增加三倍 ;) - user1534422

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接