Home >Web Front-end >JS Tutorial >JS code to randomly select x non-duplicate data from an array
This article mainly introduces the JS code for randomly picking x pieces of non-duplicate data from an array. Friends in need can refer to it
Some operations related to arrays are often encountered in work
1. Randomly select x pieces of unique data from the data (PS: S.each below is the KISSY.each method, you can change it to a for loop)
/* 从数组arr中随机取x条不重复的数据 */ function myRand(arr,num){ var newArr = []; rand(num); //随机 x 个 function rand(k){ if(k==0){ return; } var index = Math.floor(Math.random() * arr.length); var flag = true; S.each(newArr,function(v){ if(v == arr[index]){ flag = false; } }); if(flag){ newArr.push(arr[index]); k--; } rand(k); } return newArr; }
2. From the object Randomly select x pieces of unique data
/* 随机从对象obj中取x条 */ function myRand(){ var S = KISSY; var obj={ '01':{name:'a'}, '02':{name:'b'}, '03':{name:'c'}, '04':{name:'d'}, '05':{name:'e'}, '06':{name:'f'}, '07':{name:'g'}, '08':{name:'h'}, '09':{name:'i'}, '10':{name:'g'} }; var arr = []; S.each(obj,function(v,k){ arr.push(k); }); //随机取3个 var newArr = myRand(arr,3); S.each(newArr,function(b){ console.log(obj[b]); }) };
3. Remove duplicates from the array
/* 去除数组的重复项 */ function uniqArr(arr){ function toObject(a) { var o = {}; for (var i=0, j=a.length; i<j; i=i+1) { o[a[i]] = true; } return o; }; function keys(o) { var a=[], i; for (i in o) { if (o.hasOwnProperty(i)) { // 这里, YUI源码中是lang.hasOwnProperty(o, i) a.push(i); } } return a; }; return keys(toObject(arr)); }
The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video tutorial !