
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
Alternative Shuffle in JavaScript
Alternative Shuffle
An alternatively shuffled array in JavaScript is an array of Numbers in which numbers are indexed such that greatest number is followed by the smallest element, second greatest element is followed by second smallest element and so on.
For example: If the input array is −
const arr = [11, 7, 9, 3, 5, 1, 13];
Then the output should be &minus
const output = [13, 1, 11, 3, 9, 5, 7];
Example
Following is the code −
const arr = [11, 7, 9, 3, 5, 1, 13]; const sorter = (a, b) => a - b; const alternateShuffle = (arr) => { const array = arr .slice() .sort(sorter); array.sort((a, b) => a-b); for(let start = 0; start < array.length; start += 2){ array.splice(start, 0, array.pop()); } return array; }; console.log(alternateShuffle(arr));
Output
This will produce the following output in console −
[ 13, 1, 11, 3, 9, 5, 7 ]
Advertisements