- 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
Returning an array containing last n even numbers from input array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a number as the second argument.
Our function should pick and return an array of last n even numbers present in the input array.
Example
Following is the code −
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const num = 3; const pickEvens = (arr = [], num = 1) => { const res = []; for(let index = arr.length - 1; index >= 0; index -= 1){ if (res.length === num){ break; }; const number = arr[index]; if (number % 2 === 0){ res.unshift(number); }; }; return res; }; console.log(pickEvens(arr, num));
Output
[4, 6, 8]
Advertisements