J Johnson
J Johnson

Reputation: 145

Remove duplicate values in a bidimensional array starting from index 0

Which is the best way to remove duplicate values from bidimensional array? For example, my array looks like this:

var bid_array = [[1,2,3,4,5],[3,4,6,7,8,2],[7,2,4,9,11,15],[10,12,3,7,11]];

I need to start evaluating the bid_array[0] and check if bid_array[1], bid_array[2] or bid_array[3] contains a value that already exist in the bid_array[0], if exist delete the value duplicated from conflict array and when we have finished to check the last array now start from the second index position (bid_array[1]) and go ahead again to check the next sub-arrays.

I was trying this, but only works if there are just 1 value duplicated max two times. Example:

for (var i = 0; i < 8; i++) {
  for (var j = 0; j < bid_array.length; j++) {
    for (var k = (j + i); k < bid_array.length; k++) {
      for (var l = 0; l < bid_array[k].length; l++) {
        if (bid_array[j].indexOf(bid_array[k][l]) > -1) {
          bid_array[k].splice(l, 1);
        }
      }
    }
  }
}

I want that the original array that before was:

var bid_array = [[1,2,3,4,5],[3,4,6,7,8,2],[7,2,4,9,11,15],[10,12,3,7,11]];

Be, after remove all duplicate values and just keeping one:

var bid_array = [[1,2,3,4,5],[6,7,8],[9,11,15],[10,12]];

What's the best way to do this having the security that all duplicated values was removed just keeping one? Thank you for help.

Upvotes: 0

Views: 50

Answers (3)

Jonas Wilms
Jonas Wilms

Reputation: 138267

A perfect Set usecase:

var set = new Set();
for(const array of bid_array){
 var c = 0;
 array.slice().forEach((el,i) => {
   if(set.has(el)){
      array.splice(i-(c++),1);
   }else{
       set.add(el);
   }
  }); 
 }

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386578

You could use a hash table and a check.

function unique(array) {
    var hash = Object.create(null);
    return array.map(function (a) {
        return a.filter(function (b) {
            return !hash[b] && (hash[b] = true);
        });
    });
}

var array = [[1, 2, 3, 4, 5], [3, 4, 6, 7, 8, 2], [7, 2, 4, 9, 11, 15], [10, 12, 3, 7, 11]];

console.log(unique(array));

ES5 with Set

function unique(array) {
    var hash = new Set;
    return array.map(a => a.filter(b => !hash.has(b) && hash.add(b)));
}

var array = [[1, 2, 3, 4, 5], [3, 4, 6, 7, 8, 2], [7, 2, 4, 9, 11, 15], [10, 12, 3, 7, 11]];

console.log(unique(array));

Upvotes: 1

marvel308
marvel308

Reputation: 10458

you can do it in the following way

var bid_array = [[1,2,3,4,5],[3,4,6,7,8,2],[7,2,4,9,11,15],[10,12,3,7,11]];

let map = {};
bid_array = bid_array.map(function(element){
    return element.filter(function(val){
        if(map[val])
          return 0;
        map[val] = 1;
        return 1;
    });
})

console.log(bid_array);

Upvotes: 2

Related Questions