- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Shifting certain elements to the end of array JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument.
Our function should check for all the instances of second number in the array, if there exists any, the function should push all those instances to the end of the array.
If the input array is −
const arr = [1, 5, 6, 6, 5, 3, 3];
And the second argument is 6
Then the array should become −
const output = [1, 5, 5, 3, 3, 6, 6];
Example
const arr = [1, 5, 6, 6, 5, 3, 3]; const num = 6; const shiftElement = (arr, num) => { if (arr.length === 0){ return arr }; let index = 0; for(let e of arr){ if(e !== num){ arr[index] = e; index += 1; }; } for (; index < arr.length; index++){ arr[index] = num; }; }; shiftElement(arr, num); console.log(arr);
Output
And the output in the console will be −
[ 1, 5, 5, 3, 3, 6, 6 ]
Advertisements