Shuffle Array and array of object values in javascript, PHP
#1 Javascript: in javascript, there is no array shuffle inbuilt function, so we need to find some custom solution
solution1:
01 02 03 04 05 06 07 08 09 10 | var arrData= [ { some: 1 }, { some: 2 }, { some: 3 }, { some: 4 }, { some: 5 }, { some: 6 }, { some: 7 }, ]; console.log(arrData.sort( () => Math.random() - 0.5) ); |
Solution 2:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 | function shufflearray(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } |
#2 PHP: In php array shuffle is very easy to implement because, there is a inbuilt function provided “shuffle()“
1 2 | $arrData = [{ some: 1 },{ some: 2 },{ some: 3 },{ some: 4 },{ some: 5 },{ some: 6 },{ some: 7 }]; print_r(shuffle( $arrData )); //this is used just to print output. |
#3 C# : In c# there is no direct shuffle function, so we need to use random and orderby to get the output
1 2 3 | Random rnd= new Random(); string [] arrData = [{ some: 1 },{ some: 2 },{ some: 3 },{ some: 4 },{ some: 5 },{ some: 6 },{ some: 7 }]; string [] MyRandomArray = arrData.OrderBy(x => rnd.Next()).ToArray(); |
#4 Java : Implemented via custom function
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.journaldev.examples; import java.util.Arrays; import java.util.Random; public class ShuffleArray { public static void main(String[] args) { int [] array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 }; Random rand = new Random(); for ( int i = 0 ; i < array.length; i++) { int randomIndexToSwap = rand.nextInt(array.length); int temp = array[randomIndexToSwap]; array[randomIndexToSwap] = array[i]; array[i] = temp; } System.out.println(Arrays.toString(array)); } } |
Arjun is a Full-stack developer, who is fond of the web. Lives in Chikmagalur, Karnataka, India