0

Write a function called countEvenWords which accepts an array of objects. Each of these objects will have a key of firstName with a value that is a string. Return the number of firstName values that have a length that is even.

Why is it returning everything to 0?

function countEvenWords(obj) {
    let count = 0;
    for (let key in obj) {
        if (obj[key].length % 2 === 0) {
            count++
        }
    }
    return count;
}

console.log(countEvenWords([{firstName: "Mark"}, {firstName: "Sasha"}])); // 1
console.log(countEvenWords([{firstName: "Tanya"}, {firstName: "Sasha"}])); // 0
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
JuanDraper
  • 49
  • 5

2 Answers2

1

Your loop isn't looping over the objects directly, it's looping through the array (because that's what you passed into the function), so you have to drill deeper into the array to get to the firstName key from the object in the array that you want to inspect.

function countEvenWords(obj) {
    let count = 0;
    for (let key in obj) {
        if (obj[key]["firstName"].length % 2 === 0) {
            count++
        }
    }
    return count;
}

console.log(countEvenWords([{firstName: "Mark"}, {firstName: "Sasha"}])); // 1
console.log(countEvenWords([{firstName: "Tanya"}, {firstName: "Sasha"}])); // 0
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Your function expects to get a single object and iterate over its properties. But you're passing an array of objects instead. You can combine them into a single object.

function countEvenWords(obj) {
    let count = 0;
    for (let key in obj) {
        if (obj[key].length % 2 === 0) {
            count++
        }
    }
    return count;
}

console.log(countEvenWords({name1: "Mark", name2: "Sasha"})); // 1
console.log(countEvenWords({name1: "Tanya", name2: "Sasha"})); // 0

Or you can use nested loops to iterate over the array elements and object properties.

function countEvenWords(array) {
  let count = 0;
  array.forEach(obj => {
    for (let key in obj) {
      if (obj[key].length % 2 === 0) {
        count++
      }
    }
  });
  return count;
}

console.log(countEvenWords([{firstName: "Mark"}, {firstName: "Sasha"}])); // 1
console.log(countEvenWords([{firstName: "Tanya"}, {firstName: "Sasha"}])); // 0
Barmar
  • 741,623
  • 53
  • 500
  • 612