Home > Web Front-end > JS Tutorial > How to randomly sort js array

How to randomly sort js array

不言
Release: 2018-07-09 17:11:31
Original
1921 people have browsed it

This article mainly introduces the method of random sorting of js arrays, which has certain reference value. Now I share it with everyone. Friends in need can refer to it.

Method 1:

        function getRandomInt(min, max) {          return Math.floor(Math.random() * (max - min + 1) + min)
        }

        function shuffle(arr) {
          let _arr = arr.slice()          for (let i = 0; i < _arr.length; i++) {
            let j = getRandomInt(0, i)
            let t = _arr[i]
            _arr[i] = _arr[j]
            _arr[j] = t
          }          return _arr
        }
        console.log(shuffle([11,22,33,4,5,6]))
Copy after login

Method 2:

arr.sort(function(){
            Math.random()>0.5?1:-1
        })
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study , please pay attention to the PHP Chinese website for more related content!

Related recommendations:

js method of obtaining the current domain name, Url, relative path and parameters and specifying parameters

js Native left swipe to delete

The above is the detailed content of How to randomly sort js array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template