We are required to write a JavaScript function that takes in a string and returns the character from the string that appears for the second most number of times.
Example
The code for this will be −
const arr = [5, 2, 6, 7, 54, 3, 2, 2, 5, 6, 7, 5, 3, 5, 3, 4];
const secondMostFrequent = arr => {
const map = arr.reduce((acc, val) => {
if(acc.has(val)){
acc.set(val, acc.get(val) + 1);
}else{
acc.set(val, 1);
};
return acc;
}, new Map);
const frequencyArray = Array.from(map);
return frequencyArray.sort((a, b) => {
return b[1] - a[1];
})[1][0];
};
console.log(secondMostFrequent(arr));Output
The output in the console −
2