Home > Software engineering >  The filter() method
The filter() method

Time:11-19

const nums = [0,10,20,30,40,50];
nums.filter( function(num) {
    return num > 20;
})

please breakdown the code in a simple way I'm a newbiew :) help me guys to understand this more clearly.

How can we display the filtered value here? how to display the returned values?

I understood the other code like

function canVote(age)
{
    return age>=18;
}
function func(){
    var filtered = [22,34,12,23,56,12,11,1].filter(canVote);
    console.log(filtered);
}
func();

but I am not being able to understand the return type code

CodePudding user response:

I think what your talking about is creating the function inside the filter and the return statement made.

When a return statement is made it is actually the condition. In this case checking if the current number is above 20. If so then add it to the array that will be created by the filter

My prefrence for filter functions is using an arrow function like so

let arr = [0, 19, 21, 22]
let filterd = arr.filter(num => num > 20); // for one param you dont need () around parameters
let filterd2 = arr.filter((num, index) => {
  if (num < 20) {
    return [num, index]
  }
};

console.log(filterd)// logs "[21, 22]"
console.log(filterd2)// logs "[[0, 0][19, 1]]"
  • Related