0

I have an array (generated dynamically) which contains objects. Those objects contains arrays which sometimes are duplicated.

I wonder how could I make a function to check the arrays contained in the objects to see if they're duplicated.

In javascript.

Tried using the following function, but it will only check the objects in the first sub-array. Won't work on other sub-arrays.

var check = function (a){
                var retval = [];
                for (var j = 0, u = a.length; j < u; j++) {
                    if (a[j].items && a[j].items.length > 1){

                        check(a[j].items);
                    }
                    for (var k = j + 1, v = a.length; k < v; k++) {
                        if (a[j] && a[k]){
                            if (a[j]._id == a[k]._id) {

                            }
                            else{
                                retval.push(a[j]);
                            }
                        }
                    }
                }
                return retval;
            };
xjose97x
  • 41
  • 2
  • 4

1 Answers1

0

You could use recusion for this.

Example: https://jsfiddle.net/89agjx2c/

var init = function(){
  var one = new Array();
  var two = new Array();

  root = new Array();
  root.push(one);
  root.push(two);

  var one_one = {'id': 1, 'name':"one_one"};
  var one_two = {'id': 2, 'name':"one_two"};

  var two_one = {'id': 3, 'name':"one_two"};
  var two_two = {'id': 1, 'name':"one_one"};

  one.push(one_one);
  one.push(one_two);

  two.push(two_one);
  two.push(two_two);
}

this.check = function(_array){
  for (var element in _array) { 
    if( Object.prototype.toString.call( _array[element] ) === '[object Array]'){
            // Found an array
      this.check(_array[element]);
    } else{
      // Found an object
      toCheck = JSON.stringify(_array[element]);
      counter = 0;

            this.checkDuplicates(root, toCheck);
            if(counter == 2){
        console.log("duplicate found for item: " + toCheck)
      }
    }
  }
}

this.checkDuplicates = function(_array, toCheck){
  for (var element in _array) { 
    if( Object.prototype.toString.call( _array[element] ) === '[object Array]'){
            // Found an array
      this.checkDuplicates(_array[element], toCheck);
    } else{
      // Found an object
      if(JSON.stringify(_array[element]) === toCheck){
        counter++;
      }
    }
  }
}

init();
check(root);
Niek Vandael
  • 394
  • 1
  • 3
  • 15