简体   繁体   English

如何从javascript中的数组中删除某些匹配条件的元素?

[英]How do I remove certain elements matching criteria from an array in javascript?

I have an array.我有一个数组。

const arr = ['apple', 'banana', 'pear', 'orange', 'peach'];

The test function is like this.测试功能是这样的。

function test(str) {
  return str.length >= 6;
}

I can find the elements easily with filter method.我可以使用filter方法轻松找到元素。 But I want to remove these elements from the array.但我想从数组中删除这些元素。

The result should be结果应该是

['apple', 'pear', 'peach']

Javascript has a function just for this, Array.prototype.filter : Javascript 有一个函数, Array.prototype.filter

const arr = ['apple', 'banana', 'pear', 'orange', 'peach'];
function test(str) {
    return str.length >= 6;
}

// we need to negate the result since we want to keep elements where test returns false
console.log(arr.filter(x => !test(x)));
// logs: ['apple', 'pear', 'peach']

Beside the given Array#filter approach除了给定的Array#filter方法

array.filter(string => !test(string))

you could take the advantage of a functional approach which takes a function and retuns the negated result of it.您可以利用函数方法的优势,该方法采用函数并重新调整它的否定结果。

 function test(str) { return str.length >= 6; } function not(fn) { return (...args) => !fn(...args); } const array = ['apple', 'banana', 'pear', 'orange', 'peach'], result = array.filter(not(test)); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM