0

I have an array which has 2 forEach loops as below.

array1.forEach(o1 => unique_array2.forEach(o2 => {
 if (o1.uName == o2.uName && o1.uid == o2.uid) {
    //matches.push(o1);
    break;
   }
}));

If a match is found I want to exit the loop there itself. I tried to put a break but it says illegal break statement since its inside a loop.

I can create another false array and put all the negative values like below:

  if (o1.uName == o2.uName && o1.uid == o2.uid) {
    matches.push(o1);        
   }
  else{
     nonMatches.push(o1);
   } 

And then check for nonMatches array and then return accordingly. But I was trying to avoid it as my array could be big and I wanted to stop once the match is found.

Here is my snippet if required:

var array1 = [{
    id: 0,
    name: "adam",
    uName: "aSilver",
    uId: "123",
    table: "table1"
  },
  {
    id: 1,
    name: "john",
    uName: "jBerlin",
    uId: "456",
    table: "table1"
  }
];

var array2 = [{
    id: 0,
    name: "adam",
    uName: "aSilver, jBerlin",
    uId: "123, 456",
    createdBy: "auto",
    createdOn: "09/10/2018",
    desc: "none",
    table: "table1"
  },
  {
    id: 1,
    name: "john",
    uName: "aSilver, jBerlin",
    uId: "123, 456",
    createdBy: "auto",
    createdOn: "09/10/2018",
    desc: "none1",
    table: "table1"
  },
  {
    id: 0,
    name: "steve",
    uName: "aSilver, jBerlin, pParis",
    uId: "123, 456, 789 ", 
    createdBy: "auto ", 
    createdOn: "09 / 10 / 2018 ",
    desc: "none2", 
    table: "table2"
  },
  {
    id: 0,
    name: "nash",
    uName: "aSilver, jBerlin, pParis",
    uId: "123, 456, 789 ", 
    createdBy: "auto ", 
    createdOn: " 09 / 10 / 2018 ", 
    desc: "none3 ", 
    table: "table2"
  },
  {
    id: 0,
    name: "sand",
    uName: "aSilver",
    uId: "123",
    createdBy: "auto",
    createdOn: "09/10/2018",
    desc: "none4",
    table: "table3"
  }
];

obj = {};
array2.forEach(o => obj[o.table] = o);
unique_array2 = Object.keys(obj).map(k => obj[k]);
matches = [];
array1.forEach(o1 => unique_array2.forEach(o2 => {
    if (o1.uName == o2.uName && o1.uid == o2.uid) {
        //matches.push(o1);
        break;
    }
}));

console.log(matches);

Any other workarounds?

kaka1234
  • 770
  • 3
  • 9
  • 30
  • 1
    If you want to use `break` you just need to use a `for()` loop instead of a `forEach`. – Narm Sep 20 '18 at 19:11
  • Just use `some`, or a regular loop and return; if you're not collecting values you don't need to save anything. – Dave Newton Sep 20 '18 at 19:12
  • @DaveNewton I tried to use some intead of forEach above, changing in both places I use. But once a match is found, it still loops till the end. – kaka1234 Sep 20 '18 at 19:21
  • Can anyone share how can I use some instead of forEach in above. I am using 2 forEach in my above code. – kaka1234 Sep 20 '18 at 19:40

0 Answers0