我们需要编写一个JavaScript函数,该函数接受具有重复值的文字数组。我们的函数应返回数组中最常见元素的数组(如果两个或多个元素出现相同次数的大多数时间,则该数组应包含所有这些元素)。
为此的代码将是-
const arr1 = ["a", "c", "a", "b", "d", "e", "f"]; const arr2 = ["a", "c", "a", "c", "d", "e", "f"]; const getMostCommon = arr => { const count = {}; let res = []; arr.forEach(el => { count[el] = (count[el] || 0) + 1; }); res = Object.keys(count).reduce((acc, val, ind) => { if (!ind || count[val] > count[acc[0]]) { return [val]; }; if (count[val] === count[acc[0]]) { acc.push(val); }; return acc; }, []); return res; } console.log(getMostCommon(arr1)); console.log(getMostCommon(arr2));
输出结果
控制台中的输出将是-
[ 'a' ] [ 'a', 'c' ]