繁体   English   中英

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

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

我有一个数组。

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

测试功能是这样的。

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

我可以使用filter方法轻松找到元素。 但我想从数组中删除这些元素。

结果应该是

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

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']

除了给定的Array#filter方法

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

您可以利用函数方法的优势,该方法采用函数并重新调整它的否定结果。

 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