Shift certain array elements to front of array - JavaScript


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
]

Updated on: 30-Sep-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements