我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
当前回答
2019年,我们仍在调整阵列,所以我的方法是:
常量src=[…'abcdefg'];常量shuffle=arr=>[…arr].还原右((res,_,__,s)=>(res.push(s.splice(0|Math.random()*s.length,1)[0]),res),[]);console.log(shuffle(src));.作为控制台包装{最小高度:100%}
其他回答
// Create a places array which holds the index for each item in the
// passed in array.
//
// Then return a new array by randomly selecting items from the
// passed in array by referencing the places array item. Removing that
// places item each time though.
function shuffle(array) {
let places = array.map((item, index) => index);
return array.map((item, index, array) => {
const random_index = Math.floor(Math.random() * places.length);
const places_value = places[random_index];
places.splice(random_index, 1);
return array[places_value];
})
}
const arr = [
{ index: 0, value: "0" },
{ index: 1, value: "1" },
{ index: 2, value: "2" },
{ index: 3, value: "3" },
];
let shuffle = (arr) => {
let set = new Set();
while (set.size != arr.length) {
let rand = Math.floor(Math.random() * arr.length);
set.add(arr[rand]);
}
console.log(set);
};
shuffle(arr);
使用Ramda的功能解决方案。
const {map, compose, sortBy, prop} = require('ramda')
const shuffle = compose(
map(prop('v')),
sortBy(prop('i')),
map(v => ({v, i: Math.random()}))
)
shuffle([1,2,3,4,5,6,7])
使用生成器功能的ES6压缩代码*
这是通过从未屏蔽阵列的副本中随机移除项目,直到没有剩余项目。它使用新的ES6生成器功能。
设arr=[1,2,3,4,5,6,7]函数*洗牌(arr){arr=[…arr];而(arr.length)产生arr.splice(Math.random()*arr.length|0,1)[0]}console.log([…shuffle(arr)])
或者,使用ES6和拼接:
设arr=[1,2,3,4,5,6,7]let shuffled=arr.reduce(([a,b])=>(b.push(…a.splice(Math.random()*a.length |0,1)),[a,b]),[[…arr],[]])[1]console.log(混洗)
或者,ES6索引交换方法:
设arr=[1,2,3,4,5,6,7]let shuffled=arr.reduce((a,c,i,r,j)=>(j=数学随机()*(a.length-i)|0,[a[i],a[j]]=[a[j],a[i]],a),[…arr])console.log(混洗)
var shuffle = function(array) {
temp = [];
originalLength = array.length;
for (var i = 0; i < originalLength; i++) {
temp.push(array.splice(Math.floor(Math.random()*array.length),1));
}
return temp;
};