K
K
Kusmich2016-01-04 23:35:00
JavaScript
Kusmich, 2016-01-04 23:35:00

How to check 2 arrays and remove the same values?

Suppose there is an array there is an array

a = {"a": "17","b": "1","d": "3","v": "10","e": "4","f": "9"}
and there is a second array
b = {"a": "1","b": "3","d": "4","v": "5","e": "6","f": "7"}

How can I find out what values ​​are in array a and not in array b ? or how to find out what values ​​are in array b and not in array a . That is, for example, we compare the array acb , and as a result of the comparison, we should find out that the array a has the values ​​17, 10 9 which are not in the array b. Or we compare bca , and as a result of the comparison, we should find out that there are 5, 6, 7 in the array b, which are not in the array a .

How to make such comparisons?

I initially solved that problem by merging these two arrays by removing completely repeating elements, leaving the current unique. Now the task has become to find out in which of the arrays there are certain unique elements. This doesn't work...

if you combine these two arrays and then leave the current unique values, you get {17, 10, 9, 5, 6, 7}. But then we will not know the current and from which particular array the unique elements. How to find out?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2016-01-05
@Kusmich

How how? Handles! Only these are not arrays, but objects with fields.

var a = {"a": "17","b": "1","d": "3","v": "10","e": "4","f": "9"};
var b = {"a": "1", "b": "3","d": "4","v": "5", "e": "6","f": "7"};

function search(a, b) {
  var result = [];
  for(var akey in a) {
    var found = false;
    for(var bkey in b) {
      if (a[akey] == b[bkey]) {
        found = true;
        continue;
      }
    }
    if (!found) {
      result.push(a[akey]);
    }
  }
  return result;
}

console.log(search(a, b));

We are looking for each element of array A in array B. If we do not find it, then we add it to the resulting array.
And now an example with arrays.
var a = [17, 1, 3, 0, 4, 9];
var b = [1, 3, 4, 5, 6, 7];

function search(a, b) {
  var result = [];
  for(var i = 0; i < a.length; i++) {
    if (b.indexOf(a[i]) == -1) {
      result.push(a[i]);
    }
  }
  return result;
}

console.log(search(a, b));
console.log(search(b, a));

Or like this:
var a = [17, 1, 3, 0, 4, 9];
var b = [1, 3, 4, 5, 6, 7];

function search(a, b) {
  var result = [];
  a.forEach(function(v) {
    if (b.indexOf(v) == -1) {
      result.push(v);
    }
  });
  return result;
}

console.log(search(a, b));
console.log(search(b, a));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question