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

4
  • 1
    loopOverArray() doesn't return anything + Working with objects - JavaScript | MDN Commented Jul 6, 2021 at 10:27
  • You're missing this important requirement: there is an empty object saved as a variable which stores each direction Commented Jul 6, 2021 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. Commented Jul 6, 2021 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 Commented Jul 6, 2021 at 11:40

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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"]));

1 Comment

You should probably explain what counts[direction] = (counts[direction] || 0) + 1; does to someone who is new to JS.
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

Comments

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"]);

Comments

-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')}`);

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.