Randomly retrieve x JS code from the array that does not repeat data
This article mainly introduces the JS Code for randomly retrieving x records of non-duplicated data from the array. If you need it, please refer to it.
Some operations related to arrays are often encountered at work.
1. Randomly retrieve x non-duplicated data from the data (PS: The following S. each is the KISSY. each method. You can change it to a for loop)
The Code is as follows:
/*
Random acquisition of x non-repeated data from 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 retrieve x non-duplicated data from the object
The Code is as follows:
/*
Randomly retrieve x entries 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 );
});
// Random 3
Var newArr = myRand (arr, 3 );
S. each (newArr, function (B ){
Console. log (obj [B]);
})
};
3. Remove repeated items in the array
The Code is as follows:
/*
Remove repeated items from the array
*/
Function uniqArr (arr ){
Function toObject (){
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, the YUI source code is lang. hasOwnProperty (o, I)
A. push (I );
}
}
Return;
};
Return keys (toObject (arr ));
}