
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Shift Certain Array Elements to Front of Array in 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 ]
Advertisements