1

I looked at this very popular SO question:

How to merge two arrays of JSON objects

Where the OP has this:

   var array1 = ["Vijendra","Singh"];
   var array2 = ["Singh", "Shakya"];

Then he says, "I want the output to be:"

   var array3 = ["Vijendra","Singh","Shakya"];

My question is "How do you just get Singh as a result?"

   var array3 = ["Singh"];

In other words, how do you combine two arrays and only keep data that are common to both? I've looked at merge, concat, intersect, and other options, but I can't seem to get this.

Community
  • 1
  • 1
smoore4
  • 4,520
  • 3
  • 36
  • 55

1 Answers1

2

You could filter e.g. the first array array1 from the elements which are also present in the second array2 array.

var array1 = ["Vijendra","Singh"],
    array2 = ["Singh", "Shakya"],
    res = array1.filter(v => array2.indexOf(v) > -1);
    
    console.log(res);
kind user
  • 40,029
  • 7
  • 67
  • 77
  • 1
    Thank you. Apparently this question is a dupe, but I find "merge two arrays" to be much more intuitive than "array intersection" and I didn't find the other post. Your approach works. – smoore4 Apr 08 '17 at 22:26
  • @SQLDBA My pleasure – kind user Apr 08 '17 at 22:28