Intermediate Algorithm Scripting - Sorted Union

I am so stuck on this problem. Im just trying to extract the values of this multidimensional array into one array to start. Haven’t even gotten removing duplicate values. This just keeps getting harder and harder for me. I tried forEach() on the arguments to somehow remove duplicate elements of the arrays, but can’t seem get that do anything( Im not good with filter or forEach). Really struggling with the Intermediate Algorithms right now, any help would be appreciated.

Your code so far

function uniteUnique(arr) {
let unique = [];
  for (let i of arguments) {
// looping inner array elements
  for (let j of i) {
    unique.push([j])
  }}
    return unique; } 

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


``
This is the result im getting:

[ [ 1 ], [ 3 ], [ 2 ], [ 5 ], [ 2 ], [ 1 ], [ 4 ], [ 2 ], [ 1 ] ]


Intermediate Algorithm Scripting - Sorted Union
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union

Update, I have changed the for Loop and now it looks like this, with the current result in console.

function uniteUnique(arr) {
let unique = [];
  for (let i of arguments) {
// looping inner array elements
  for (let j of i)
  if(arr.indexOf(i[j]) === -1) 
   {
    unique.push(j)
  }}
    return unique; } 

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

result:

[ 3, 5, 4, 2 ]

That is closer to what you want.

  1. Are you sure you are checking the correct array using indexOf?

  2. Are you sure you are pushing the correct thing? Remember, you already have access to the most inner elements using j


Personally, I would use includes instead of indexOf

Ok thank you for your input. I’ll try your suggestion and play around with it to see if it works.

I solved it! I did indexOf on the empty array.

 for (let i of arguments) {
// looping inner array elements
  for (let j of i)
  if(unique.indexOf(j) === -1) 
   {
    unique.push(j)
  }}
    return unique; }

I saw same structure from similar examples I found online, but still dont understand why I had to do it on the empty array as opposed to my input array.

1 Like

Good Job, Keep it up Mate!

Because it is the unique array, you need to check for unique values. If it already contains the value, it shouldn’t be added again.

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