1

Please help! I need to declare an empty array (foodTray = []), and run a loop 5x (for each iteration push a food type), the foodTray has to hold a max of 2 types but the total length should not exceed 5.

const foodTypes = ['seafood', 'nuts', 'seeds'];

I had done this =>

'use strict';

let foodTray = [];
const foodTypes = ['seafood', 'nuts', 'seeds'];
for (let x = 0; x < foodTypes.length; x++) {
  const food = foodTypes[x];
  foodTray.push(food); 
  if (foodTray.length < 5) {
    foodTray.push(food); 
  }
}
console.log('I have ' + `${foodTray}.`);

but I was instructed the loop had to run 5 times***** and what I used was the length of the foodTypes.

The desired output should be => I have seafood, seafood, nuts, nuts, seeds.

The problem: I did for (let x = 0; x < *foodTypes.length*; x++) instead, the loop should run 5 times! I am not sure how I can iterate twice over an element.

4
  • 1
    Could you please clarify what's the problem and what is the desired output? Commented Oct 3, 2020 at 22:32
  • 2
    Well it seems your code is working fine and you are getting your desired output, what is the problem? Commented Oct 3, 2020 at 22:42
  • do you mean to add the first 5 twice? if you want it to run over the first 5 foodtypes you could change the for loop : for (let x = 0; x < foodTypes.length && x < 5; x++) but I'm not sure I understand the desired output.. Commented Oct 3, 2020 at 22:42
  • perhaps you could count the number of food in your foodtray and add it to your if statement? while (foodTray.length < 5 && foodTray.filter(f => f == food).length < 2) { foodTray.push(food)} Commented Oct 3, 2020 at 22:45

1 Answer 1

3

Your original code is giving you the desired output which is : I have seafood, seafood, nuts, nuts, seeds.

let foodTray = [];
const foodTypes = ['seafood', 'nuts', 'seeds'];
for (let x = 0; x < foodTypes.length; x++) {
  const food = foodTypes[x];
  foodTray.push(food); 
  if (foodTray.length < 5) {
    foodTray.push(food); 
  }
}
console.log('I have ' + `${foodTray}.`);

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

Comments

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.