首页 > 解决方案 > 从数组中返回字符串出现的对象(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']))

谢谢!

标签: javascriptarrays

解决方案


试试这个,它给出了预期的结果。不过,我们可以缩短这个逻辑。

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}

推荐阅读