Sorted Union-Need Help

Sorted Union-Need Help
0

#1

Tell us what’s happening:

I cannot figure out how to filter out the duplicates. Please help.

Your code so far

  let newArr = [];
  newArr.push(...arguments);
  console.log(newArr);
  let finalArr = [];
  let sortedArr = [];

  for (i = 0; i < newArr.length; i++) {
    for (j = 0; j < newArr[i].length; j++) {
      finalArr.push(newArr[i][j]);
    }
  }
  console.log(finalArr);
  sortedArr = finalArr.filter(function(item) {
    return item !== item;
  })

  return sortedArr;

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union


#2

First the FCC tests console tells you i is not defined. You should always declare variables inside your functions, to avoid creating globally scoped variables. The same goes for the variable j.

After that, you have some logic issues you need to figure out.

For the test case you have shown above, your function should return [1, 3, 2, 5, 4],
but instead returns [ 1, 3, 2, 5, 2, 1, 4, 2, 1 ].


#3

Yes exactly. I merged the arrays into one so I can apply filter on only 1 array for duplicates.


#4

I am just facing an issue in the filtering section. Cannot make logic for checking and removing duplicates.


#5

So i was able to solve the problem.

function uniteUnique(arr) {
  let newArr = [];
  newArr.push(...arguments);
  console.log(newArr);
  let finalArr = [];
  let sortedArr = [];

  for (var i = 0; i < newArr.length; i++) {
    for (var j = 0; j < newArr[i].length; j++) {
      finalArr.push(newArr[i][j]);
    }
  }
  console.log(finalArr);
  sortedArr = finalArr.filter(function(item, index, self) {
    if(index == self.indexOf(item)) {
      return item;
    }
  })

  return sortedArr;


}

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