Was it helpful?

Question

Shift certain array elements to front of array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function takes in an array of numbers. The function should bring all the 3-digit integers to the front of the array.

Let’s say the following is our array of numbers −

const numList = [1, 324,34, 3434, 304, 2929, 23, 444];

Example

Following is the code −

const numList = [1, 324,34, 3434, 304, 2929, 23, 444];
const isThreeDigit = num => num > 99 && num < 1000;
const bringToFront = arr => {
   for(let i = 0; i < arr.length; i++){
      if(!isThreeDigit(arr[i])){
         continue;
      };
      arr.unshift(arr.splice(i, 1)[0]);
   };
};
bringToFront(numList);
console.log(numList);

Output

This will produce the following output in console −

[
  444, 304,  324,
    1,  34, 3434,
 2929,  23
]
raja
Published on 30-Sep-2020 17:59:27
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top