Delete duplicate array elements

后端 未结 2 778
旧巷少年郎
旧巷少年郎 2021-01-27 08:26

i have the following loops that goes through an array.

for(var j=0; j<10;j++) {
  for(var k=0; k<10; k++) {

    if(final[k]==ya[j]){
      final[k].change         


        
相关标签:
2条回答
  • 2021-01-27 08:33

    If you don't want to use any framework, thats the code:

    function mix(first_arr, second_arr) {
        for(i = 0; i < second_arr.length; i++) {
            if(first_arr.indexOf(second_arr[i]) == -1) {
                first_arr.push(second_arr[i]);
            }
        }
        return first_arr;
    }
    

    See in action http://jsfiddle.net/jwAmA/

    PD: Use arrays [] instead of objects {}

    0 讨论(0)
  • 2021-01-27 08:47

    Your sample data isn't quite valid. Is this what you mean? http://jsfiddle.net/B74Gm/

    var final = {
        1: {score:0},
        2: {score: 2},
        3: {score: 0},
        4: {score: 5},
        5: {score: 1},
        6: {score: 10}, 
        7: {score: 10}
    },
    
    ya = {
        2: {score: 2},
        10: {score: 3}, 
        4: {score: 0},
        15: {score: 0},
        6: {score: 4},
        17: {score: 5}
    }; 
    
    for (var i in ya) {
        final[i] = final[i] || {score: 0};
        final[i].score += ya[i].score;
    }
    
    0 讨论(0)
提交回复
热议问题