Diff Two Arrays problem in basic javascript

The prompt is:
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
Note: You can return the array with its elements in any order.

I am really lost on how to continue solving this. This is the code I have written so far:

function diffArray(arr1, arr2) {
  let stupidArr = [x];
  let same = 0;
  for(let i = 0; i < arr1.length; i++) {
    same = 0;
    for(let k = 0; k < arr2.length; k++) {
      if(arr1[i] == arr2[k]) {
        same++;
      }
    }
    if(same == 0) {
      stupidArr.push(arr[i]);
    }
  }
  return stupidArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Just curious, what is the purpose of same?
Structure-wise, you’re on the right path.
If you’re stuck you might want to pseudocode: defining in plain english, the steps you need to do to achieve your goal, (you can read about POLYA’s approach to problem solving. e.g:

Input: Numbers in two Arrays
Output: a New Array with unique number from two arrays
Steps:
1. Create an array to contain the result;
2. Iterate through the first array with a for loop;
3. Check every element in the first loop against every element in the second array by having a nested (inner) for loop to iterate through the elements in the second array;
4. Create a conditional if else statement: if element1 is equal to element2, push into result array;
5. After the looping is done, then return the result array.

Once you’re done with that, then you can start coding. Modify the steps if while coding there’s something need change.
You can also research about double loop / nested loop in JS.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

let stupidArr = [ x ]; // since x is not defined it will throw an error, instead it should be [ ]

In order to get the elements that are member of one of the array not both.

1. loop through 1st array and push in  studpidArr only those elements that are not in 2nd array

2. loop through 2nd array and push in  studpidArr only those elements that are not in 1st array

hint: arr1.indexOf(x)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.