Skip to content
Advertisement

Find matching values in two arrays

I want to find the matching values between two arrays and create a json array setting true if the values matched or false if they didn’t. I know, that the values in the secondArray will always match some values from the first array and that it will always be smaller, because the secondArray is created based on the first one.

let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];

I want to create a json array:

[
  {
    "name": "One",
    "matched": false
  },
  {
    "name": "Two",
    "matched": false
  },
  {
    "name": "Three",
    "matched": true
  },
  {
    "name": "Four",
    "matched": true
  },
  {
    "name": "Five",
    "matched": false
  }
]

Normally, I would do something like this:

            firstArray.forEach(firstElement=>{
              secondArray.forEach(secondElement=>{
                  if(firstArray.indexOf(secondElement)>=0){
                      jsonArray.push({'name': secondElement, 'matched': true});
                  }else{
                      jsonArray.push({'name': secondElement, 'matched': false});
                  }
              });
          });

But this just creates a json array with duplicated values where the name is the same, but the matched value are falsed and true.

It seems like I’m getting lost in something very simple.

Advertisement

Answer

You can use the combination of map and includes helper to achieve that.

let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];

jsonArray = firstArray.map(i => {
   return { 'name': i, 'matched': secondArray.includes(i) };
});

console.log(jsonArray);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement