javascript JS 中 [].filter 的反转?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20148276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:52:40  来源:igfitidea点击:

Inverse of [].filter in JS?

javascriptarraysfilter

提问by user2958725

I realize that I can do:

我意识到我可以做到:

arr = arr.filter(function(n){ return !filterFunc(n); });

But is there any way to just invert a filter without wrapping the filterer in an anon function?

但是有没有什么方法可以在不将过滤器包装在 anon 函数中的情况下反转过滤器?

It just seems cumbersome.

只是看起来很麻烦。

回答by apscience

You can use an arrow function:

您可以使用箭头函数:

const a = someArr.filter(someFilter);
const a = someArr.filter(e => !someFilter(e));

回答by Sascha

Lodashprovides a reject function that does the exact opposite of filter.

Lodash提供了一个与过滤器完全相反的拒绝函数。

arr = _.reject(arr, filterFunc);

回答by sudee

Take a look at lodash's negatefunction. It does exactly what @Yury Tarabankomentions in his comment.

看看 lodash 的negate函数。它完全符合@Yury Tarabanko在他的评论中提到的内容。

Usage:

用法:

arr = arr.filter(_.negate(filterFunc));

回答by SEoF

I wasn't happy with any of the answers directly, and actually wound up using newer JS features

我对任何直接的答案都不满意,实际上最终使用了较新的 JS 功能

arr.filter(() => ! filterfunc(...arguments));

This beats most of the others by not having to respecify the context (this) at any point by using an arrow functionand passing all parameters accordingly using the spread syntaxon the arguments object.

this通过使用箭头函数并在参数对象上使用扩展语法相应地传递所有参数,无需在任何时候重新指定上下文 ( ),从而击败了大多数其他方法。

It's also rather succinct, though I would rather an invert flag on the filter function, or a separate function.

它也相当简洁,尽管我更喜欢过滤器函数上的反转标志,或者一个单独的函数。

The question might be a little on the old side, but it's still relevant.

这个问题可能有点陈旧,但它仍然是相关的。

回答by James Lai

filterreturns elements which return truein your evaluation. If you want to inverse that, inverse your logic it within the function which tests each element.

filter返回true在您的评估中返回的元素。如果您想反转它,请在测试每个元素的函数中反转您的逻辑。

Then, you could simply make this function work like so:

然后,您可以简单地使这个函数像这样工作:

arr = arr.filter(filterFunc);

arr = arr.filter(filterFunc);

回答by Mr. Polywhirl

You can either add your own function or add a static/prototype methods to the Array object.

您可以添加自己的函数或向 Array 对象添加静态/原型方法。

Code

代码

Array Polyfill Methods

数组填充方法

/**
 * The not() method creates a new array with all elements that fail
 * the test implemented by the provided function.
 *
 * Syntax
 * arr.not(callback[, thisArg])
 *
 * @param  callback
 *         Function to test each element of the array. Invoked with
 *         arguments (element, index, array). Return true to keep
 *         the element, false otherwise.
 * @param  thisArg
 *         Optional. Value to use as this when executing callback.
 * @return Returns a new array containing all the items which fail
 *         the test.
 */
Array.prototype.not = function(callback) {
    return this.filter(function () {
        return !callback.apply(this, arguments);
    });
};
/**
 * Static method which calls Array.prototype.not on the array
 * paramater.
 *
 * @see Array.prototype.not
 */
Array.not = function (array, callback) {
    return array != null ? array.not(callback) : [];
};

Custom Function

自定义功能

function unfilter(array, callback) {
    return array.filter(function () {
        return !callback.apply(this, arguments);
    });
}

This is safer to use than a polyfill, but it doesn't look as elegant in use.

这比 polyfill 使用起来更安全,但它在使用中看起来并不优雅。

unfilter(items, isFruit)vs items.not(isFruit)

unfilter(items, isFruit)对比 items.not(isFruit)

Example

例子

// ================================================================
// Polyfill
// ================================================================
Array.prototype.not = function(callback) {
    return this.filter(function () {
        return !callback.apply(this, arguments);
    });
};

// ================================================================
// Main
// ================================================================
var items = [{
    name: 'Apple',
    isFruit: true
}, {
    name: 'Carrot',
    isFruit: false
}, {
    name: 'Melon',
    isFruit: true
}, {
    name: 'Potato',
    isFruit: false
}];

var isFruit = function(item, index) {
    return item != null && item.isFruit;
};
var getName = function(item, index) {
    return item != null ? item.name : '?';
};

document.body.innerHTML = items.not(isFruit).map(getName).join(', ');

回答by Gaurav

Lets take an example

让我们举个例子

var cars = [
  {carname: "indica", brand: "Tata"},
  {carname: "accord", brand: "Toyota"},
  {carname: "vento", brand: "volkswagen"},
  {carname: "polo", brand: "volkswagen"},
  {carname: "Manza", brand: "Tata"},
  {carname: "Agile", brand: "Chevrolet"},
];

var isTata = function(car) {
  return cars.species === "Tata"
}

var dogs = cars.filter(isTata); // retuns objects of brand Tata

in reverse of this just change your logic

与此相反,只需改变你的逻辑

var isNotTata = function(car) {
  return cars.species !== "Tata"
}

var dogs = cars.filter(isNotTata); // returns objects of brand other than Tata