0

In the following code sample I understand that this bit of code does not find the unique value in the given array, but I am not wondering how to solve the toy problem, but wondering why the output contains the value 5 twice. [1, 2, 3, 4, 5, 5]

let arr = [1,2,3,4,5,5,3,2,1];

function findUniq(arr) {
  let other = [];
  let reduced = arr.reduce(function(allNums, num){
    if(num in allNums) {
      other.push(num);
    } else {
      allNums.push(num);
    }
    return allNums;
  }, []);
  return reduced;
}

console.log(findUniq(arr));

It seems to me that when arr[5] gets evaluated it should use the first part of the 'if statement' and push it into the 'other' array. (But maybe I'm not understanding the 'in' operator correctly)

smcgee31
  • 91
  • 1
  • 7
  • 5
    the 'in' keyword is checking keys, not values. Use Array.prototype.includes instead – ndugger Feb 26 '17 at 17:00
  • so then why is arr[6] not also pushed into allNums? – smcgee31 Feb 26 '17 at 17:02
  • 2
    @smcgee31 At `arr[6]` `if(num in allNums)` evaluates to `if(3 in [1, 2, 3, 4, 5, 5])` which evaluates to `true`, because the index `3` (which is `4`) exists in the array, _not_ because the value `3` exists in the array. – Sebastian Simon Feb 26 '17 at 17:04
  • `if (allNums.indexOf(num) !== -1) {...}` ? `indexOf` returns -1 if no value found or, if it has found something, the index of the value in the array. – rkeet Feb 26 '17 at 17:06
  • Ahh! now that makes sense. So I didn't actually understand the 'in' operator. Thanks so much! – smcgee31 Feb 26 '17 at 17:07
  • Note that you can do all this in ES6 with `findUniq = arr => [...new Set(arr)];`. NB: the `other` array serves no purpose in your code. – trincot Feb 26 '17 at 17:10
  • @trincot That's an awesome bit to add to my small but growing bag of JS knowledge - Thanks! – smcgee31 Feb 26 '17 at 17:33

0 Answers0