0
var array1 = ["AL", "CA", "IN "];
var array2 = ["AL", "AL", "CA", "CA", "IN", "IN", "WI", "WY"];

My desired o/p:

["AL", "CA", "IN"]
var array1 = ["AL", "CA", "I"];
var array2 = ["AL", "AL", "CA", "CA", "IN", "IN", "WI", "WY"];

My desired o/p:

["AL", "CA"]

I tried like this:

const intersection = array1.filter(element => array2.includes(element));

console.log(intersection) But i am getting o/p : ["AL", "CA"]. Can some one help me on this.

I want to compare 2 arrays and find the result with matched elements,I searched a lot but could not get a solution .please help me in advance.

  • 1
    Your actual output seems to match your expected output. What's exactly the problem? Is the extra space after `IN` tripping you up? Is that a typo? – Robby Cornelissen Jun 08 '21 at 05:08
  • in 1) `array1[2]` has a space at the end. – VLAZ Jun 08 '21 at 05:09
  • You have a space at the end of `"IN "`. If it is a typo, remove that. Or, you can use `array2.includes(element.trim())` – adiga Jun 08 '21 at 05:13
  • I want to compare array1 with array 2 and want the o/p with matched elements Suppose:var array1 = ["AL", "CA", "IN "]; var array2 = ["AL", "AL", "CA", "CA", "IN", "IN", "WI", "WY"]; When i am comparing above 2 arrays i want 0/p :["AL", "CA", "IN "] but getting ["AL", "CA" ]; – Pavan Kumar Jun 08 '21 at 05:15
  • `"IN " === "IN"` is `false`, that's why you don't get matches. You have different strings. As adiga said, either remove the space from `"IN "` manually or `.trim()`. – VLAZ Jun 08 '21 at 05:20
  • i copied ur code and spend like 5 minutes and finally realized u have a mistake in ur array. "IN" and "IN " are different – Rupak Jun 08 '21 at 05:23
  • Understood ThanK You Roby,VLAZ,adiga – Pavan Kumar Jun 08 '21 at 05:30

0 Answers0