- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a function which returns only even numbers in JavaScript array?
Here, we need to write a function that takes one argument, which is an array of numbers, and returns an array that contains only the numbers from the input array that are even.
So, let's name the function as returnEvenArray, the code for the function will be −
Example
const arr = [3,5,6,7,8,4,2,1,66,77]; const returnEvenArray = (arr) => { return arr.filter(el => { return el % 2 === 0; }) }; console.log(returnEvenArray(arr));
We just returned a filtered array that only contains elements that are multiples of 2.
Output
Output in the console will be −
[ 6, 8, 4, 2, 66 ]
Above, we returned only even numbers as output.
Advertisements