-
Notifications
You must be signed in to change notification settings - Fork 0
JS Array Prototype Filter
The filter()
method creates a new array with all elements that pass the test implemented by the provided function
arr.filter(callback[, thisArg])
| Parameter | Description
-------- | --------- | ------------------------------------------------- Required | arr | Array being filtered Required | callback | Function with 3 arguments (element, index, array) Optional | thisArg | Value of this while executing callback
Return: A new array that contains all the values for which the callback function returns true. If the callback function returns false for all elements of arr, the length of the new array is 0.
| Parameter | Description
-------- | --------- | --------------------------------------- Optional | element | current element of array being filtered Optional | index | current index of array being filtered Optional | array | current array being filtered
// Define a callback function.
function CheckIfPrime(value, index, ar) {
high = Math.floor(Math.sqrt(value)) + 1;
for (var div = 2; div <= high; div++) {
if (value % div == 0) {
return false;
}
}
return true;
}
// Create the original array.
var numbers = [31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53];
// Get the prime numbers that are in the original array.
var primes = numbers.filter(CheckIfPrime);
document.write(primes);
// Output: 31,37,41,43,47,53
// Create the original array.
var arr = [5, "element", 10, "the", true];
// Create an array that contains the string
// values that are in the original array.
var result = arr.filter(
function (value) {
return (typeof value === 'string');
}
);
document.write(result);
// Output: element, the
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links