计算 JavaScript 数组元素的出现次数并放入新的二维数组中
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 16:44:17
我们需要编写一个 JavaScript 函数,该函数接受一个文字值数组。然后,该函数应计算输入数组中每个元素的频率并在此基础上准备一个新数组。
例如 − 如果输入数组是 −
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
那么输出应该是 −
const output = [ [5, 3], [2, 5], [9, 1], [4, 1] ];
示例
其代码为 −
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequencyArray = (arr = []) => {
const res = [];
arr.forEach(el => {
if (!this[el]) {
this[el] = [el, 0];
res.push(this[el])
};
this[el][1] ++
}, {});
return res;
};
console.log(frequencyArray(arr));
输出
控制台中的输出将是 −
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

