Skip to content

shuffleArray() Helper Method

The shuffleArray() Helper Method module provides a helper function that accepts an array and returns a new array in a shuffled order.

Import

To import the shuffleArray() Helper Method:

javascript
import { shuffleArray } from '@obewds/vueventus'

Arguments

Returns: Array

ArgsTypeStatusDescription
arrayArray (Generic)RequiredFunction requires an array and can accept a generic type

Use Example

javascript
const numbersArray = [ 1, 2, 3, 4, 5 ]

const mixedArray = [ '1', 2, ['three'], {four: 'four'}, false ]

const newNumbers = shuffleArray(numbersArray)

const newMixed = shuffleArray(mixedArray)

console.log( newNumbers )
// returns a shuffled variation of [ 1, 2, 3, 4, 5 ]

console.log( newMixed )
// returns a shuffled variation of [ '1', 2, ['three'], {four: 'four'}, false ]

Module Code

ts
// ./src/helpers/shuffleArray.ts

export default function<Type>(array: Type[]): Type[] {

    let newArray = [...array]
    
    for (let i = newArray.length - 1; i > 0; i--) {

        // get a random index
        let j = Math.floor(Math.random() * (i + 1))

        // swap elements
        let t = newArray[i]
        newArray[i] = newArray[j]
        newArray[j] = t

    }

    return newArray

}

Released under the MIT License