Instructions
There is an array with some numbers. All numbers are equal except for one. Try to find it!
For example:
findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
Itโs guaranteed that array contains at least 3 numbers.
My solution:
function findUniq(arr) {
let repeated = arr.filter((item, index) => arr.indexOf(item) !== index)
return arr.filter((item)=> item !== repeated[0])[0]
}
Explanation
First I made an array that contained the values that were repeated , I filtered the array leaving only the items that their index in the array isn't equal to the index being iterated, so I get the repeated elements.
let repeated = arr.filter((item, index) => arr.indexOf(item) !== index)
Input --> [ 1, 1, 1, 2, 1, 1 ]
Output --> [ 1, 1, 1, 1 ]
After that I filtered the initial array again, and checked if the ietm being iterated is equal to the first element of the repeated array, and after that I returned the first value of that array, because it returned the result inside of an array.
return arr.filter((item)=> item !== repeated[0])[0]
Input --> [ 1, 1, 1, 2, 1, 1 ]
Output --> [ 2 ] --> 2
What do you think about this solution? ๐๐ค
Top comments (6)
Thanks for the comment bro ๐ฅ, I understand what you want to do, you'll check every item and then check the element next to it and the element behind it so you know if they're equal, but when you test it, remember that the problem gives you an array with only 2 numbers (the repeated one and the unique one), you are testing it with a lot of different numbers, so it returns the first number that is different to the 2 next to it
I don't know if this would work with the last element of the array, because index+1 doesn't exist, or with the first one because the element index-1 doesn't exist.
Either way I think it's a great solution, you just need to adapt it a little bit more to the problem ๐
Keep going!! ๐ช
You can use the array methods
find
andlastIndexOf
/indexOf
to do this in a more direct manner:find
has the added advantage overfilter
that it stops iterating after the first match. Sorting the array will only work for numbers, strings or objects that can be coerced to either.Great solution for optimizing the code, thanks bro! ๐๐ฅ
Sort the array, check if first two elements are equal - if they are, unique is last element, otherwise it's the first element
Makes sense bro, great solution! ๐