Horje
How to Randomly Rearrange an Object in JavaScript ?

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 }



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Find the Index of an Element that Contains the Given Substring in Array ? How to Find the Index of an Element that Contains the Given Substring in Array ?
What are Ternary Operator in JavaScript? What are Ternary Operator in JavaScript?
Maximum Frequency Character in String in JavaScript Maximum Frequency Character in String in JavaScript
JavaScript Program to Calculate Power Using Recursion JavaScript Program to Calculate Power Using Recursion
Replace all Occurrences of a Substring in a String in JavaScript Replace all Occurrences of a Substring in a String in JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12