Reputation: 33
I am begginer at JavaScript and currently training at Code Wars, and I have some problems with my code here. I got a task to find a number in a given array, that differs from the other numbers in the same array. When I run the tests only at those two specific arrays the code returns 'undefined'. So I wanted to know why and how should I improve my code? Maybe I missed something. Appreciate your help.
Here is my code:
function findUniq(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== arr[0] && arr[i] !== arr.slice(-1)[0]) {
return arr[i];
}
}
}
So I have those two arrays:
findUniq([0, 1, 1, 1, 1, 1, 1, 1]);
expected 0
, but returns undefined
.
findUniq([8, 8, 8, 8, 8, 8, 8, 7]);
expected 7
, also returns undefined
.
Upvotes: 0
Views: 73
Reputation: 33
function findUniq(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== arr[arr.length - (i-1)] && arr[i] !== arr[arr.length + (i-1)] && arr[i] !== arr[i+1] && arr[i] !== arr[i-1]) {
return arr[i];
}
}
}
Well here is my own answer thanks to everyone, I will take to attention any critics you have, to improve.Thanks to Jonas Wilms:)
Upvotes: 0
Reputation: 50807
Perhaps the simplest way is, as Jonas Wilms suggested, to find the first one that is not equal to both its predecessor and its successor, wrapping around at the end of the list:
const findUnique = arr => arr.find((n, i, a) =>
n !== a[(i - 1) % arr.length] && n !== a[(i + 1 % arr.length)]
)
console.log(findUnique([1, 1, 3, 1, 1, 1, 1, 1])) //~> 3
console.log(findUnique([0, 1, 1, 1, 1, 1, 1, 1])) //~> 0
console.log(findUnique([8, 8, 8, 8, 8, 8, 8, 7])) //~> 7
Note that this uses %
, the remainder or modulus operator of Javascript to handle sliding off the end of the list.
Upvotes: 0
Reputation: 37755
You can also use reduce to club digits as key-value pair and than find the key which has value 1
function findUniq(input){
let op = input.reduce((op,inp)=>{
if(op[inp]){
op[inp]++;
} else {
op[inp] = 1
}
return op
},{})
return Object.keys(op).find(e=> op[e] === 1)
}
console.log(findUniq([0, 1, 1, 1, 1, 1, 1, 1]))
console.log(findUniq([8, 8, 8, 8, 8, 8, 8, 7]))
Upvotes: 1
Reputation: 138457
For every element in the array you check wether it unequals the first and the last position:
//❌ ✔️
//🔽 🔽
[0, 1, 1, 1, 1, 1, 1, 1]
//⬆️
Now for the first element (which is the one to find), comparing to the last element will result in "unequal", because 0 is not 1, but checking for the first will result in "equal" as you compare the elementto itself.
For it to detect the first and last element, don't check if it unequals both the first and the last, but wether it unequals the previous and the next, then jump back to the end or beginning when the index leaves the array.
Through that it also works for the last and the first element:
// ✔️ ✔️
// 🔽 🔽
[0, 1, 1, 1, 1, 1, 1, 1]
//⬆️
Upvotes: 0