Returning an array containing last n even numbers from input array in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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]
raja
Published on 20-Apr-2021 09:43:12
Advertisements