在lodash中返回不包括索引n的数组

7

现在我有这个函数:

function without(array, index) {
    array.splice(index, 1);
    return array;
}

我认为这应该是lodash可以提供的实用程序,但看起来不是这样。
有了这个函数,我可以进行一行代码的链式操作:
var guestList = without(guests, bannedGuest).concat(moreNames);

没有办法在不使用 Lodash 的情况下实现这一点,除非引入一个谓词函数?

2
既然你已经知道如何做,使用lodash解决方案有什么意义呢? - user663031
1
我们在项目中已经广泛使用了lodash。lodash有许多用于数组的辅助函数。因此,我想应该有一个lodash函数可以让我用一行代码完成与“without”相同的操作。 - core
1
它必须是索引还是值也可以?lodash有几个函数可以使用值而不是索引 - withoutdifference,并且它有pullAt,它可以做你想要的事情,但返回删除的值,因此无法链接。 - Sean Vieira
1个回答

3

_.without 已经存在。或者,您也可以使用_.pull,它会改变给定的参数数组。

var guests = ['Peter', 'Lua', 'Elly', 'Scruath of the 5th sector'];
var bannedGuest = 'Scruath of the 5th sector';
var bannedGuests = ['Peter', 'Scruath of the 5th sector'];

console.debug(_.without(guests, bannedGuest )); // ["Peter", "Lua", "Elly"]

禁止一组来宾的功能不是直接支持的,但我们可以轻松地绕过这个问题:
// banning an array of guests is not yet supported, but we can use JS apply:
var guestList = _.without.apply(null, [guests].concat(bannedGuests));
console.debug(guestList); // ["Lua", "Elly"]

// or if you are feeling fancy or just want to learn a new titbit, we can use spread:
guestList = _.spread(_.without)([guests].concat(bannedGuests));
console.debug(guestList); // ["Lua", "Elly"]

jsFiddle

或者你也可以查看_.at_.pullAt,它们具有类似的行为,但是使用数组索引而不是对象进行删除。


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