I came across a basic question of array in javascript of list out the recurring elements or duplicate elements in an array of strings.
So, lets say we have an array, arr = ['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan','Tom', 'John']
So now I tried to solve this by below approach:
var duplicate = [];
function duplicateValues (arr) {
let l = arr.length;
for (let i=0; i<l; i++){
if(arr[i+1] == arr[i]) {
duplicate.push(arr[i]);
}
}
return duplicate;
}
duplicateValues(['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan','Tom', 'John']
);
Expected output:
['Ash', 'Bob', 'Dylan']
But I am getting an empty array in the console. What should be the best approach to solve this problem?
4
Answers
This should be very simple, look below.
Wouldn’t that be easier?
All you need to do is to just check if a map has that key.
You could use
reduce
to get the frequency of each name in the array, then filter only those entries that appear with a frequency of 2 or more.This approach avoids the use of
find
andindexOf
, which would scan over the array an unnecessary number of times.