0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【javascript】配列のシャッフル2

Last updated at Posted at 2021-04-11

前回の記事でsortが微妙だったのでreduceで書いてみた。

#コード

//要素の入れ替え関数
const swap = (a,i,j) => ( [a[i], a[j]] = [a[j], a[i]], a );
//reduceの内部処理
const reducer = (p,_,i,$,m=p.length-i) => swap(p, m-1, Math.floor(Math.random() * m));
//本体
const shuffleArray = arr => arr.reduce(reducer, arr.slice());

console.log(shuffleArray( [...Array(15).keys()]) );

色んなものを犠牲にした。

#一つにまとめた(追記)

const shuffleArray = arr => 
	arr.reduce((p,_,i,$,m=p.length-i,r=Math.floor(Math.random()*m--)) => 
		([p[m], p[r]] = [p[r], p[m]], p ), arr.slice());

console.log(shuffleArray( [...Array(15).keys()]) );
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?