w3resource

JavaScript: Randomize the order of the values of an array, returning a new array

JavaScript fundamental (ES6 Syntax): Exercise-145 with Solution

Randomize Array Values

Write a JavaScript program to randomize the order of array values, returning an updated array.

  • Use the Fisher-Yates algorithm to reorder the elements of the array.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2

// Define the shuffle function
const shuffle = ([...arr]) => {
  let m = arr.length;
  // Iterate over the array elements
  while (m) {
    // Pick a random index
    const i = Math.floor(Math.random() * m--);
    // Swap the current element with a random element
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  // Return the shuffled array
  return arr;
};

// Test the shuffle function with an array
const foo = [1, 2, 3];
console.log(shuffle(foo)); // Output: A shuffled version of the input array

Output:

[2,1,3]

Visual Presentation:

JavaScript Fundamental: Randomize the order of the values of an array, returning a new array.

Flowchart:

flowchart: Randomize the order of the values of an array, returning a new array

Live Demo:

See the Pen javascript-basic-exercise-145-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get an array of elements that appear in both arrays.
Next: Write a JavaScript program to create a shallow clone of an object.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-145.php