Home > database >  Why is this 2D array comparison not working?
Why is this 2D array comparison not working?

Time:03-20

So, I got:

array1 = 
[
 ["Fisrt Name1", "Last Name1", "[email protected]"],
 ["Fisrt Name2", "Last Name2", "[email protected]"],
 ["Fisrt Name3", "Last Name2", "[email protected]"]
]
array2 = 
[
 ["[email protected]"],
 ["[email protected]"],
]

I'm trying to compare them and keep uniques from array1 in the following ways and it should return:

resultingArray = 
[
 ["Fisrt Name1", "Last Name1", "[email protected]"],
 ["Fisrt Name3", "Last Name2", "[email protected]"]
]

...but it's returning everything.

Attemp1:

resultingArray = array1.filter(e => !array2.includes(e));

Attemp2:

let resultingArray = [];
for (let a = 0; a < array1.length; a  ){
    for (let n= 0; n < array2.length; n  ){
      if(array1[a][2].indexOf(array2[n][0]) === -1){
        resultingArray.push(array1[a])
      }
    }
  } 

Thanks for helping!

CodePudding user response:

Here's my final edited answer after refactoring the code.

array1 = [
    ['Fisrt Name1', 'Last Name1', '[email protected]'],
    ['Fisrt Name2', 'Last Name2', '[email protected]'],
    ['Fisrt Name3', 'Last Name3', '[email protected]'],
    ['Fisrt Name4', 'Last Name4', '[email protected]'],
];

array2 = [['[email protected]'], ['[email protected]']];

let resultingArray = [];
first: for (let a = 0; a < array1.length; a  ) {
    second: for (let n = 0; n < array2.length; n  ) {
        if (array1[a][2] === array2[n][0]) {
            continue first;
        }
    }
    resultingArray.push(array1[a]);
}

console.log(resultingArray);

Here I've used labels. More about labels.

CodePudding user response:

You can not compare 2 reference values ( array or object) Maybe something like

array1 = [
    ['Fisrt Name1', 'Last Name1', '[email protected]'],
    ['Fisrt Name2', 'Last Name2', '[email protected]'],
    ['Fisrt Name3', 'Last Name3', '[email protected]'],
    ['Fisrt Name4', 'Last Name4', '[email protected]'],
];

array2 = [['[email protected]'], ['[email protected]']];

const result = array2.map(item => array1.filter(e => !e.includes(item[0])))

console.log(result)

  • Related