const filtered = array.filter(item => {
return item < 20;
});
// An example that will loop through an array
// and create a new array containing only items that
// are less than 20. If array is [13, 65, 101, 19],
// the returned array in filtered will be [13, 19]
// The filter() method creates a new array with all elements
// that pass the test implemented
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
// filter(): returns a new array with all elements that pass the test
// If no elements pass the test, an empty array will be returned.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
const oddFiltration = (arr) => {
const result = arr.filter(n => n%2);
return (result);
}
//if you find this answer is useful ,
//upvote ⇑⇑ , so can the others benefit also . @mohammad alshraideh ( ͡~ ͜ʖ ͡°)
// let arr = [1,2,3]
/*
filter accepts a callback function, and each value of arr is passed to the
callback function. You define the callback function as you would a regular
function, you're just doing it inside the filter function. filter applies the code
in the callback function to each value of arr, and creates a new array based on your
callback functions return values. The return value must be a boolean, which denotes whether an element
should be keep or not
*/
let filteredArr = arr.filter(function(value){
return value >= 2
})
// filteredArr is:
// [2,3]
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// function to check even numbers
function checkEven(number) {
if (number % 2 == 0)
return true;
else
return false;
}
// create a new array by filter even numbers from the numbers array
let evenNumbers = numbers.filter(checkEven);
console.log(evenNumbers);
// Output: [ 2, 4, 6, 8, 10 ]
/* What is the filter() method?
This method returns all the elements of the array that satisfy the condition
specified in the callback function.
*/
const x = [1, 2, 3, 4, 5];
const y = x.filter(el => el*2 === 2);
console.log("y is: ", y); // y is: [1]
/* If you check out the output of the above example,
the value of y is an array of 1 element that satisfies the condition.
This is because the filter() method iterates over all elements of the array and
then returns a filtered array which satisfy the condition specified.
*/