1

Hi guys I'm stuck on a practice question, and really can't figure out a good solution.

The question is:

"The loopOverArray() function takes an array of directions as an argument and there is an empty object saved as a variable which stores each direction and how many times it was in the array. Using a for loop, this function needs to loop over each element in the array and update the object to show how many times each direction was found in the array."

The expected output should look like:

loopOverArray(["n", "s", "e", "e"] ==> returns {n: 1, s: 1, e: 2}
loopOverArray(["north", "south", "south", "north"] ==> returns {north: 2, south: 2}
loopOverArray([]) ==> returns {}

This is what i've tried so far. I'm new to JS so please forgive the very clumsy attempt.

function loopOverArray(directions) {
        let ncount = 0;
        let ecount = 0;
        let scount = 0;
        let wcount = 0;
 

    for (let direction of directions) {

        if (direction == "n") {
            ncount += 1;
        } else if (direction == "e") {
            ecount += 1;
        } else if (direction == "s") {
            scount += 1;
        } else {
            wcount += 1;
        }
    }
        console.log(`n: ${ncount}, s: ${scount}, e: ${ecount}, w: ${wcount}`)
}

loopOverArray(["n", "n", "s"]);

Problem is I think this doesn't satisfy the questions requirements properly, and its very ugly besides. There must be a better way. Any help would be humbly appreciated

zedd0
  • 31
  • 4
  • 1
    `loopOverArray()` doesn't return anything + [Working with objects - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects) – Andreas Jul 06 '21 at 10:27
  • You're missing this important requirement: `there is an empty object saved as a variable which stores each direction` – georg Jul 06 '21 at 10:30
  • your approach has no issues. it is good. you iterating array only once. you can use switch to avoid if else as every if else condition will be checked. – Amit Verma Jul 06 '21 at 10:36
  • @AmitVerma _"your approach has no issues"_ - Only if you ignore the fact that it does not what the requirement says it should do o.O – Andreas Jul 06 '21 at 11:40

5 Answers5

1

We crate an empty object

let counts = {};

and loop through directions array.

In each iteration, we check either we already have direction count in counts object or consider 0 instead and then increment by 1.

counts[direction] = (counts[direction] || 0) + 1;

function loopOverArray(directions) {
  let counts = {};
  for (const direction of directions) {
    counts[direction] = (counts[direction] || 0) + 1;
  }
  return counts;
}

console.log(loopOverArray(["n", "s", "e", "e"]));
Azhar Zafar
  • 1,554
  • 1
  • 10
  • 13
  • You should probably explain what `counts[direction] = (counts[direction] || 0) + 1;` does to someone who is new to JS. – Andy Jul 06 '21 at 10:44
1

There's a requirement that you use an object. So you're almost there. Just think of your variable names, your directions, as object property keys instead.

function loopOverArray(directions) {

  // Define the object
  const obj = {};

  for (let direction of directions) {

    // If the object key (the direction) on the object doesn't exist
    // create it and set the value to zero
    if (!obj[direction]) obj[direction] = 0;

    // Then just increment the value
    obj[direction] += 1;
  }

  // And then return the object from the function
  // once all the array iterations are done
  return obj;

}

console.log(loopOverArray([ 'n', 'n', 's' ]));
console.log(loopOverArray([ 'north', 'north', 'south', 'east' ]));
Andy
  • 61,948
  • 13
  • 68
  • 95
0

check if this works for you:

var counts = {};
for (var i = 0; i < yourArray.length; i++) {
    counts[yourArray[i]] = 1 + (counts[yourArray[i]] || 0);
}

You can check more answers here: Count unique elements in array without sorting

BRABO
  • 100
  • 7
0

you can try this

function loopOverArray(directions) {
    let result = {}
    for (let direction of directions) {
        direction in result ? result[direction]++ : result[direction] = 1
    }
    console.log(result)
}
loopOverArray(["n", "n", "s"]);
-2
function findOccurences(directions,elementToFind){    
    var result = directions.reduce(function (elementToFind, total, number){
            return total += number==elementToFind;
        }.bind(this, elementToFind), 0);
    return result;
}
var ar = ['n', 'e', 'w', 's', 's', 's','e', 'e'];   
        
console.log(`n: ${findOccurences(ar, 'n')}, s: ${findOccurences(ar, 's')}, e: ${findOccurences(ar, 'e')}, w: ${findOccurences(ar, 'w')}`);
Suresh Kumar
  • 11,241
  • 9
  • 44
  • 54
  • This is a practice question for someone new to JS who 1) has to use a `for/loop`, and 2) is going to be more confused because you've provided no explanation for what your code does. 3) Why are you using `bind`? – Andy Jul 06 '21 at 10:55