Intermediate Algorithm Scripting - Sorted Union using if not in array to push elements in array

Tell us what’s happening:
I have added all the arrays from function calling into b and tried to add only elements in array ar if they aren’t already in ar (like trying to add unique elements as they appear)…it isn’t working for two case …however it is working for three cases.
What can I do ?

Your code so far

function uniteUnique(arr) {
  //console.log(arr);
  let a=Object.values(arguments).slice(1);
  let b=[...arr];
  for (let i=0;i<a.length;i++){
    for(let j=0;j<a[i].length;j++){
      b.push(a[i][j])
    }
  }
  console.log(b)
  let ar=[];
  for(let i=0;i<b.length;i++){
    if (b[i] in ar){
      continue
    }
    else{
      ar.push(b[i]);
    }
  }
  console.log(ar);

  return ar;
}

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

Challenge: Intermediate Algorithm Scripting - Sorted Union

Link to the challenge:

Take a closer look at the in operator, it doesn’t seem to actually check if value is in array.

What would you suggest how use to ' in ' properly to check if the element is in array ?

It cannot do that, see in operator - JavaScript | MDN

Array have few methods capable to check if specified element is contained in it. contains and indexOf to mention couple of them.

1 Like

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