0

How to check first element of an array 1 with all elements in array 2, then second element in array 2, repeat, using JS for loop? or a JS method?

var array1 = ['1','2','3','4','5','6','7']

var array2 = ['43','24','35','42','55','63','1']

So, in the above code, we would check all elements in array1 against 43, then all elements in array 1 against 24 etc.

The output would remove any instances from array1 that match any instances in array 2 and add it to the end. So the output would be

array1 = ['2','3','4','5','6','7', '1']
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Leafyshark
  • 395
  • 2
  • 5
  • 11

3 Answers3

0

u can do that with simple loop or u can use lodash library:)

_.difference([2, 1], [2, 3]);

// => [1]
Vasyl Gutnyk
  • 4,813
  • 2
  • 34
  • 37
0

You can do this by using forEach on first array.

For example:

array1.forEach(elem1 => {
  var index = array2.indexOf(elem1);
  if (index != -1) {
    array2.splice(index, 1);
  } else {
    array2.push(elem1);
  }
});

In this example you iterate through array1 and search for position of each array1 element. If you find one, then it will be removed.

Gregor Doroschenko
  • 11,488
  • 5
  • 25
  • 37
0

You can use array#reduce to segregate values of array1 into unique array and repeating array and then array#concat both of them.

var array1 = ['1','2','3','4','5','6','7'],
    array2 = ['43','24','35','42','55','63','1'],
    set = new Set(array2);
    
var result = array1.reduce((r,v) => (set.has(v) ? r.repeating.push(v) : r.unique.push(v), r), {unique:[], repeating:[]});

var output = result.unique.concat(result.repeating);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can also use array#includes to check for value in the other array.

var array1 = ['1','2','3','4','5','6','7'],
    array2 = ['43','24','35','42','55','63','1'];
    
var result = array1.reduce((r,v) => (array2.includes(v) ? r.repeating.push(v) : r.unique.push(v), r), {unique:[], repeating:[]});

var output = result.unique.concat(result.repeating);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51