JS code that does not duplicate data is randomly selected from the array

  • 2020-03-30 01:01:24
  • OfStack

Some operations related to arrays are often encountered in work

1. Randomly select x pieces of non-repeating data from the data (PS: the following s.ach is the kissy.each method, which can be changed into the for loop)



 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 non-repeating data from the object



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);
    });
    //I'm going to pick 3 at random
    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)) { //In this case, the YUI source is lang. HasOwnProperty (o, I)
                a.push(i);
            }
        }
        return a;
    };
    return keys(toObject(arr));
}


Related articles: