Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/array/randomIndices.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* 数组下表随机排序(洗牌算法)
* @author 凌霄云上 <[email protected]>
* @category array
* @alias yd_array_randomIndices
* @param {Array} array
* @returns {Array} 返回随机下标数组
* @summary 这个函数保持原有数组顺序,根据随机下标数组获取
* @example
* yd_array_randomIndices(['a','b','c','d','d','e']); 数组下标[0-5]
* 结果:可能是[5,3,4,0,1,2]
* }
*/

export default (arr) =>{
const indices = Array.from(arr.keys());
for (let i = indices.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[indices[i], indices[j]] = [indices[j], indices[i]];
}
return indices;
};