How to randomize subset of array in Javascript?

后端 未结 4 1616
死守一世寂寞
死守一世寂寞 2021-01-25 18:22

What is the best way to randomize part of the array in Javascript

For example, if I have 100 items in the array, what is the fast and efficient way of randomizing set of

4条回答
  •  心在旅途
    2021-01-25 19:18

    I would just use the built in slice, concat and sort methods. Something like this.

    function shuffle(arr, start, end) {
     return arr.slice(start, end).sort(function() { return .5 - Math.random(); }).concat(arr.slice(end));
    };

    That's the basic idea, you probably want to make an algorithm to slice every 10 elements, sort and rejoin the sets.

    EDIT: Read comments below for why this solution may not be suitable for your needs.

提交回复
热议问题