Reorder an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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

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

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

[
   444, 304, 324,
   1, 34, 3434,
   2929, 23
]
raja
Published on 22-Oct-2020 12:55:17
Advertisements