JavaScript Array Operations: Filter

node v16.18.0
version: 1.0.0
endpointsharetweet
Filter creates a new array with all elements that pass the test implemented by the provided function.
/** * Filter creates a new array with all elements that pass the * test implemented by the provided function. * * @param {any} element - The current element. * @param {number} index (Optional) - The index of the current element. * @param {Array} array (Optional) - The array filter was called upon. */ function test (element, index, array) { /* return test result */ return element % 2 !== 0; } const odds = [0, 1, 2, 3, 4, 5].filter(test);
// Let's start with an array const numbers = [0, 5, 10, 15, 20, 25, 30];
// Let's filter all the numbers greater than 10 const greaterThan10 = numbers.filter(n => n > 10);
// Let's filter all the even numbers const evens = greaterThan10.filter(n => n % 2 === 0);
Loading…

no comments

    sign in to comment