0

I have this 2 array:

let field1 = [ 'one', 'two', 'three', 'four' ];
let field2 = [ 'one', 'three', 'six' ];

Now I want the output should be six

I am trying :

console.log( field1.filter(x => !field2.includes(x)) );

but maybe something is wrong here.

Shibbir
  • 1,963
  • 2
  • 25
  • 48

2 Answers2

1

Maybe this is what you want:

let field1 = [ 'one', 'two', 'three', 'four' ];
let field2 = [ 'one', 'three', 'six' ];
const answer = field2.filter(it => !field1.includes(it));
console.log(answer); // ['six']

Or you can use indexOf to check if any item of the second array is not present in the first array like this:

let field1 = [ 'one', 'two', 'three', 'four' ];
let field2 = [ 'one', 'three', 'six' ];
function diff(arr1, arr2) {
    const arr3 = [];
    for (const x of arr2) {
        if (arr1.indexOf(x) < 0) {
            arr3.push(x);
        }
    }
    return arr3;
}
const answer = diff(field1, field2);
console.log(answer);
code đờ
  • 554
  • 1
  • 9
  • 19
1

just swap 2 variables field1, field2

how about this?

 field2.filter(ele => !field1.includes(ele))[0]

robin14dev
  • 41
  • 4