This is a code for first recurring element and lets say as an input [2,5,5,2,3,5,1,2,4] return 5 because the pairs are before 2,2 and im not able to return 5
function firstRecurring(input) {
for (let i = 0; i < input.length; i++) {
for (let j = i + 1; j < input.length; j++) {
if(input[i] === input[j]) {
return input[i];
}
}
}
return undefined
}
console.log(firstRecurring([2,5,5,2,3,5,1,2,4]));
Your j index runs immediately to the end of the array. You should instead put a limit to how far you look and check the section before. So j should not be looking ahead, but back:
function firstRecurring(input) {
for (let i = 1; i < input.length; i++) {
for (let j = 0; j < i; j++) {
if(input[i] === input[j]) {
return input[i];
}
}
}
return undefined;
}
console.log(firstRecurring([2,5,5,2,3,5,1,2,4]));
Of course, this can be made more efficient by using a set of encountered values. You can then also use the for..of syntax. And... return undefined is really not necessary, as it is the default behaviour:
function firstRecurring(input) {
let set = new Set;
for (let val of input) {
if (set.has(val)) return val;
set.add(val);
}
}
console.log(firstRecurring([2,5,5,2,3,5,1,2,4]));