-1

Note: Im pretty sure this has been asked before, but I can't seem to find a similar solution. I believe this is called a hashmap?

I need help writing a function that returns an object with keys: (n,e,s,w), and their respective sums for the amount of string character occurrences passed from a random order array.

///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']))

Thank you!

twominds
  • 1,084
  • 5
  • 20

1 Answers1

1

Try this one, It gives expected result. We can short this logic though.

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}
Dipak Telangre
  • 1,792
  • 4
  • 19
  • 46