Home > Software design >  Removing an object from an array when it's equal to an object in another array?
Removing an object from an array when it's equal to an object in another array?

Time:07-02

I have 2 arrays and have to take out the object from one of them that is equal to one object from the other.

Like for example:

var arr1 = [1, 2, 3, 4, 5]
var arr2 = [2, 3, 4]

I've been running some for loops like this one:

for (I = 0; I < arr1.length; I  ) {
for (I2 = 0; I2 < arr2.length; I2  ){
  if (arr1[I] == arr2[I2]){}

I already tried .splice, .filter and .push but I'm not getting the desired result...

The ideal result would be that arr1 ended up containing only the values that are not also into arr2, or a new array with said values.

CodePudding user response:

If the final array won't have any duplicate values, you could always join the two arrays and then get unique values using

Array.from(new Set([...arr1, ...arr2]

This will join the two arrays with [...arr1, ...arr2]

Then get unique values by constructing a set

Then convert it back to an array with Array.from().

If the final array will have duplicate values, you can use

arr1.filter(item => {
    return !arr2.includes(item)
}

This will only return true on items that are not found in arr2.

CodePudding user response:

Remove elements in one array that equal elements in another array

function ltesto() {
  var arr1 = [1, 2, 3, 4, 5];
  var arr2 = [2, 3, 4];
  var oA = arr1.map((e, i) => {
    if (arr2.includes(e)) {
      return null;
    } else {
      return e;
    }
  }).filter(e => e);
  Logger.log(JSON.stringify(oA))
}

Execution log
2:41:01 PM  Notice  Execution started
2:41:01 PM  Info    [1,5]
2:41:02 PM  Notice  Execution completed
  • Related