“Cara Mengacak Array” Kode Jawaban

JavaScript secara acak mengocok array

function randomArrayShuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}
var alphabet=["a","b","c","d","e"];
randomArrayShuffle(alphabet); 
//alphabet is now shuffled randomly = ["d", "c", "b", "e", "a"]


Grepper

Cara Mengacak Array

const getShuffledArr = arr => {
    const newArr = arr.slice()
    for (let i = newArr.length - 1; i > 0; i--) {
        const rand = Math.floor(Math.random() * (i + 1));
        [newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
    }
    return newArr
};
Graceful Grasshopper

mengacak array

let unshuffled = ['hello', 'a', 't', 'q', 1, 2, 3, {cats: true}]

let shuffled = unshuffled
  .map((a) => ({sort: Math.random(), value: a}))
  .sort((a, b) => a.sort - b.sort)
  .map((a) => a.value)
Concerned Crossbill

Jawaban yang mirip dengan “Cara Mengacak Array”

Pertanyaan yang mirip dengan “Cara Mengacak Array”

Lebih banyak jawaban terkait untuk “Cara Mengacak Array” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya