0
function allDifferent(xs){
   for(x of xs){

        let array1 = xs;
        let index = xs.indexOf(x);
        array1.splice(index, 1);

        if(array1.includes(x)){
           return false;
        }

   }
   return true;
}

I am trying to check if every element of the array "xs" is different by removing every element one by one and then checking if the remaining array still includes the value of that element somewhere else.

btw I already solved the problem in a different way so that i don't need splice but i would just like to understand.

  • 1
    array1 is a reference to xs. You need to write xs.slice() for your code to work. – HerrAlvé Apr 03 '22 at 13:51
  • Please read [this reference on `.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). Specifically: _The splice() method **changes the contents of an array** by removing or replacing existing elements and/or adding new elements in place_. In the code in the question, the line: `let array1 = xs;` essentially makes `array1` just an alias/alternate-name to access `xs`. Hence, when `array1` mutates (ie, changes, due to `.splice()`) - so does `xs`. Please try like so: `let array1 = [...xs];` which does a shallow-copy. – jsN00b Apr 03 '22 at 13:54
  • @FelixFransen it's because in that last example you've reassigned the `copiedCounter` variable, which can't possibly affect `counter`. It's when you *mutate* a shared reference that (it appears like) two variables are both updated. (Note that also `counter` here is a simple number primitive, not an object or array, so it will get copied by value rather than reference anyway.) – Robin Zigmond Apr 03 '22 at 14:18
  • Thanks @RobinZigmond! I understand now. – Felix Fransen Apr 03 '22 at 14:25

0 Answers0