0

I'm new to JS and often do these challenges to learn JS well.

I'm here trying to work with a nested loop and trying to create a function which should returns values from schoolsB array that isn't in schoolsA so the expected output I want is:

"Edify", "Beacon House"

I think I'm halfway there with the if-else but instead, it's returning only values that are present in both arrays however I want something else!

I tried doing this:

if (!(arr2[i].includes(arr1[j]))) {

but this also didn't work!

Where am I mistaking?

PS: I do know I can simply use a filter method to achieve what I want but I wanna learn to use this too!

let schoolsA = ["Aman", "Shoeby", "Rose"];

let schoolsB = ["Aman", "Shoeby", "Edify", "Beacon House"];

function filtering(arr1, arr2) {
  let output = [];

  for (let i = 0; i < arr2.length; i++) {
    for (let j = 0; j < arr1.length; j++) {
      if (arr2[i].includes(arr1[j])) {
        output.push(arr2[i]);
      }
    }
  }

  return output;
}

console.log(filtering(schoolsA, schoolsB));
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • 2
    `schoolsB.filter(v => !schoolsA.includes(v))`: https://playcode.io/698188/ – Lawrence Cherone Oct 28 '20 at 18:04
  • 1
    Does this answer your question? [How to get the difference between two arrays in JavaScript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – johannchopin Oct 28 '20 at 18:06

2 Answers2

0

Probably you want it like this:

function filtering(arr1, arr2) {
  let output = [];
  // iterate over every element in arr2
  for (let i = 0; i < arr2.length; i++) {
      // If arr1 does not include the element arr2[i], then add it to the output
      if (!arr1.includes(arr2[i])) {
        output.push(arr2[i]);
      }
  }

  return output;
}
Rubydesic
  • 3,386
  • 12
  • 27
  • Thank you, just realised that .includes is also basically one type of for loop. – imheretolearn Oct 28 '20 at 18:16
  • @imheretolearn yea, that's why this type of algorithm is not so efficient. The best way to do this is with sets, where you only need one loop and you can remove in constant time – Rubydesic Oct 28 '20 at 18:40
0

let schoolsA = ["Aman", "Shoeby", "Rose"];

let schoolsB = ["Aman", "Shoeby", "Edify", "Beacon House"];

function filtering(arr1, arr2) {
  let output = [];

  for (let element of arr2) {
    if (!arr1.includes(element)) {
      output.push(element);
    }
  }

  return output;
}

console.log(filtering(schoolsA, schoolsB));
Simon
  • 369
  • 1
  • 9