Alternative shuffle in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
raja
Published on 18-Sep-2020 12:50:25
Advertisements