user16041868
user16041868

Reputation:

Need alternative code for comparing two array using javascript / node js

I have two arrays:

Array1 = ["home.jpg",
 "sun.jpg",
 "flower.jpg",
 "fish.jpg"
];

Array2 = ["home.jpg",
 "kite.jpg",
 "car.jpg",
 "coca.jpg",
"flower.jpg"
];

I want to compare Array1 with Array2 and store the data of Array2 which not match with Array1, so here kite.jpg, car.jpg, coca.jpg are not present inside Array1 so they should be a result.

I have a code which do distinguish the value which is not present inside Array1 and Array2:

let result = Array2.filter(function (n) {
                return !this.has(n);
              }, new Set(Array1));

But the problem here is when I am doing console.log(result); output comes like this:

["kite.jpg"]
["kite.jpg", "car.jpg"]
["kite.jpg", "car.jpg", "coca.jpg"]

I want only output like this:

["kite.jpg", "car.jpg", "coca.jpg"]

Array1=["home.jpg",
 "sun.jpg",
 "flower.jpg",
 "fish.jpg"];

Array2= ["home.jpg",
 "kite.jpg",
 "car.jpg",
 "coca.jpg",
"flower.jpg"];


let result = Array2.filter(function (n) {
                return !this.has(n);
              }, new Set(Array1));
              
              console.log(result);

Here I am getting correct output, but in my system its showing differently so is there any way I can compare and store element which are different ?

Upvotes: 0

Views: 37

Answers (1)

ikos23
ikos23

Reputation: 5364

Hard to say what's going on in your "system".

Try it this way maybe (basically the same but in a bit simpler form):

const arr1 = new Set(Array1)
const result = Array2.filter(elem => !arr1.has(elem))

Upvotes: 1

Related Questions