Assessment for JSON skill test -- creating an array and joining or checking the length at every itearation?

I just finished the Test your skills: JSON and I would like to know if there are potential improvements. Here is the code:

const catArray = JSON.parse(catString);
let mothers = [];

for (const cat of catArray) {

    mothers.push(cat.name);

    for (const kitten of cat.kittens) {
        if (kitten.gender === 'm') male++;
        total++;
    }
}

lastMother = mothers.pop();

motherInfo += mothers.join(', ') + ' and ' + lastMother + '.';
kittenInfo = `They have ${total} kittens in total. 
${male} male and ${total - male} female.`

Particularly, I was wondering if instead of pushing to mothers[], then using .join() and .pop(), it would be more or less efficient and advisable to go through an if; else if; else to check, if it is the first index, the last, or somewhere in between, at every iteration. Thanks for taking the time to read it. :slight_smile:

Answering my (couple of minutes in the) past self, quite an amount of useless operations and operations. This is of better taste:

const catArray = JSON.parse(catString);

for (const [index, cat] of catArray.entries()) {

  if (index === catArray.length - 1) {
    motherInfo += ' and ';
  }
  else if (index !== 0) {
    motherInfo += ', ';
  }

  motherInfo += `${cat.name}`;

  for (const kitten of cat.kittens) {
    if (kitten.gender === 'm') {
      male++;
    }
    total++;
  }
}

motherInfo += '.';
kittenInfo = `They have ${total} kittens in total. 
${male} male and ${total - male} female.`;

Hi @joaojgabriel and welcome to the community :wave:

Great improvements from your first version. :medal_sports:
I definitively like if..else..if better. Nice idea to use entries() to get the index in the for..of loop.

If you plan on doing more tasks it would be helpful if you could share your code in an online editor like https://codepen.io/, https://glitch.com or https://jsfiddle.net/. It’s good to have some running code where we can test things out. Thank you :blush:

Have a nice weekend,
Michael

1 Like