Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Shift certain array elements to front of array - JavaScript
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.
Let's say the following is our array of numbers:
const numList = [1, 324, 34, 3434, 304, 2929, 23, 444];
Understanding 3-Digit Numbers
A 3-digit number is any integer between 100 and 999 (inclusive). We can check this using a simple condition:
const isThreeDigit = num => num > 99 && numtrue false falseExample
Here's the complete solution that moves all 3-digit numbers to the front:
const numList = [1, 324, 34, 3434, 304, 2929, 23, 444]; const isThreeDigit = num => num > 99 && num { for(let i = 0; i[ 444, 304, 324, 1, 34, 3434, 2929, 23 ]How It Works
The algorithm works by:
- Iterating through the array: We loop through each element
-
Checking if it's a 3-digit number: Using the
isThreeDigithelper function -
Moving to front: If it's a 3-digit number, we use
splice(i, 1)[0]to remove it from its current position andunshift()to add it to the beginning -
Skipping non-3-digit numbers: We use
continueto skip elements that don't meet our criteria
Alternative Approach Using Filter
Here's a cleaner approach using array methods:
const numList2 = [1, 324, 34, 3434, 304, 2929, 23, 444];
const isThreeDigit = num => num > 99 && num {
const threeDigit = arr.filter(isThreeDigit);
const others = arr.filter(num => !isThreeDigit(num));
return [...threeDigit, ...others];
};
const result = moveThreeDigitToFront(numList2);
console.log(result);
[ 324, 304, 444, 1, 34, 3434, 2929, 23 ]
Conclusion
Both approaches successfully move 3-digit numbers to the front of the array. The splice/unshift method modifies the original array in place, while the filter method creates a new array with the desired order.
Advertisements
