Random acquisition of x pieces of javascript code without repeated data from the array _ javascript skills

Source: Internet
Author: User
Tags hasownproperty
This article mainly introduces the JS Code for randomly retrieving x records of non-duplicated data from the array. If you need it, you can refer to some operations related to the array that you often encounter 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 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 ));
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.