I often encounter some operations related to arrays at 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)
Copy the code code as follows:
/*
Randomly select x pieces of unique data from the array arr
*/
function myRand(arr,num){
var newArr = [];
rand(num); //Random 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. Randomly select x pieces of unique data from the object
Copy the code code as follows:
/*
Randomly pick x items from object obj
*/
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);
});
//Randomly pick 3
var newArr = myRand(arr,3);
S.each(newArr,function(b){
console.log(obj[b]);
})
};
3. Remove duplicates from an array
Copy the code code as follows:
/*
Remove duplicates from 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)) { // Here, in the YUI source code it is lang.hasOwnProperty(o, i)
a.push(i);
}
}
return a;
};
return keys(toObject(arr));
}