Open In App

How to Randomly Rearrange an Object in JavaScript ?

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Randomly rearranging an object in JavaScript involves shuffling its properties in a random order. This operation is particularly useful for scenarios where the order of object properties needs to be randomized, such as implementing a randomizer for game elements or shuffling quiz questions.

Using Object Entries and Array Shuffling

Convert the object into an array of key-value pairs using Object.entries() method. Shuffle the array using a shuffling algorithm, like the Fisher-Yates shuffle. Convert the shuffled array back into an object using Object.fromEntries() method.

Example: The below code uses the above-discussed approach to randomly rearrange an object in JavaScript.

Javascript




function shuffleObject(obj) {
    const entries = Object.entries(obj);
    for (let i = entries.length - 1; i > 0; i--) {
        const j =
            Math.floor(Math.random() * (i + 1));
        [entries[i], entries[j]] =
            [entries[j], entries[i]];
    }
    return Object.fromEntries(entries);
}
 
const originalObject =
    { a: 1, b: 2, c: 3, d: 4 };
const shuffledObject =
    shuffleObject(originalObject);
console.log(shuffledObject);


Output

{ c: 3, a: 1, d: 4, b: 2 }

Using Object Keys and Array Shuffling

Get the keys of the object in an array using Object.keys() method. Shuffle the array of keys using a shuffling algorithm and then create a new object by iterating over the shuffled keys and assigning the corresponding values from the original object.

Example: The below code implements above method to randomly rearrange the object in JavaScript.

Javascript




function shuffleObjectKeys(obj) {
    const keys = Object.keys(obj);
    for (let i = keys.length - 1; i > 0; i--) {
        const j =
            Math.floor(Math.random() * (i + 1));
        [keys[i], keys[j]] =
            [keys[j], keys[i]];
    }
    const shuffledObj = {};
    keys.forEach(key => {
        shuffledObj[key] = obj[key];
    });
    return shuffledObj;
}
 
const originalObject =
    { a: 1, b: 2, c: 3, d: 4 };
const shuffledObject =
    shuffleObjectKeys(originalObject);
console.log(shuffledObject);


Output

{ b: 2, d: 4, a: 1, c: 3 }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads