In a recent interview, I was tasked with finding repetitive elements in an array. While I was able to do so using a for loop, the interviewer requested a more efficient method without using a for loop. I am relatively new to exploring Java script and would appreciate any guidance on alternative approaches to identifying repetitive elements in an array. Below is the code I provided as my initial answer:
var a = [1,2,3,3,4,4,5,5,6,7,8,8,9,10,11,12];
var repeatElements = [];
for (var i=0;i<a.length;i++){
for(var j=1+i; j<a.length;j++){
if (a[i]===a[j]){
repeatElements.push(a[i]);
}
}
}
console.log(repeatElements);
I also researched similar questions on Stack Overflow such as Get all unique values in a JavaScript array (remove duplicates) to see if using filter for finding repetitive elements would be a more efficient solution.