javascript - 从数组中返回字符串出现的对象(Javascript)
问题描述
注意:我很确定以前有人问过这个问题,但我似乎找不到类似的解决方案。我相信这被称为哈希图?
我需要帮助编写一个函数,该函数返回一个带有键的对象:(n,e,s,w),以及它们各自的总和,用于从随机顺序数组传递的字符串字符出现的数量。
///If these arrays are individually passed into my function:
//ex#1: const orderedDirections = [n,e,s,w,n,e,s,w,n,e,s,w];
//ex#2: const orderedDirections = [n,n,n,e,e,e,s,s,s,w,w,w];
//ex#3: const orderedDirections = [n,e,n,e,w,e,s];
//The examples should return a hashmap object for each duplicate occurrence of a (n,e,s,w) string character:
//return ex#1: const directionOccurance = {n: 3,e: 3, s: 3,w: 3};
//return ex#2: const directionOccurance = {n: 3,e: 3, s: 3,w: 3};
//return ex#3: const directionOccurance = {n: 2,e: 3, s: 1,w: 1};
function countOccurances(dir) {
let dirOccur = {};
//return dirOccur {n:3 ,e:3 ,s:3 ,w: 3}
for(let i = 0; i < dir.length; i++){
//iterate through the string array and count the amount of occurances for each similar character. Then return it as a hashmap object such as {n: ?,: ?,s: ?,w: ?}
}
}
console.log(countOccurances(['n','e','s','w','n','e','s','w','n','e','s','w']))
谢谢!
解决方案
试试这个,它给出了预期的结果。不过,我们可以缩短这个逻辑。
function countOccurances(arr) {
let out = {}
arr.forEach(el => {
out[el] = out[el] ? out[el] + 1 : 1
});
return out;
}
console.log(countOccurances(['n', 'e', 's', 'w', 'n', 'e', 's', 'w', 'n', 'e', 's', 'w']));
//{n: 3, e: 3, s: 3, w: 3}
推荐阅读
- javascript - 在没有选中一个 jquery 的情况下禁用表的同一列中的所有复选框
- python - 如何在 django 中创建嵌套模型
- wordpress - 如何在wordpress中设置自定义永久链接
- ios - SecCertificateCopyData 返回可选数据?
- vba - 使用自动筛选后将数据从多个工作簿复制到一个工作簿
- javascript - C3 图表不从 jQuery 数据呈现
- javascript - 通过绘图图移动
- javascript - 使用 JS 计算 PHP while 循环中的元素
- tensorflow - 将 2d 张量转换为 3d 以用于 LSTM 层
- shell - 如何在shell脚本中绕过\