To get the even numbers from an array in JavaScript using the filter()
method, you can use the following code:
javascriptconst numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
In this example, the filter()
method is used to create a new array called evenNumbers
, which includes only the elements of the original numbers
array that are even.
The callback
function in the filter()
method checks if each element of the numbers
array is even or not. It returns true
for each even number, and false
for odd numbers. The filter()
method then returns a new array with all the elements that returned true
in the callback
function.
The resulting evenNumbers
array contains all the even numbers from the original numbers
array, and the output of the console.log()
statement is [2, 4, 6, 8, 10]
.
[JavaScript Interview Questions and Answers, JavaScript, JavaScript Tutorial]
Comments
Post a Comment