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. 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
:
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(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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.