JS: Loop with multiple conditions


I have an array of objects (cars), from which I want to show just the cars which "compete".

const cars = [
  {
    name: "red",
    competes: true,
    category: 1
  },
  {
   name: "blue",
   competes: false,
   category: 1
  },
  {
    name: "green",
    competes: true,
     category: 2
  },
  {
    name: "yellow",
    competes: true,
    category: 3
  }
]

But from those cars which compete, i only want to show those cars which are in category one, which is fine with a for loop.

The objects are now static but since i want to change them in a second moment, i need a code which checks if the cars compete and then checks if there are cars in "category" one.

My try was with a loop inside a loop, bit that doesnt work since it displays all multiple times

for (let i = 0; i < cars.length; i++) {
  if (cars[i].competes === false) continue;
  
  for (let f = 0; f < cars.length; f++) {
  if (cars[f].category > 1) break;
  console.log(`Cat1: ${cars[f].name}`);
}
}

How can this be resolved if the "category" attributes inside "cars" are for example all 2 or more?

const cars = [
  {
    name: "red",
    competes: true,
    category: 2
  },
  {
   name: "blue",
   competes: false,
   category: 2
  },
  {
    name: "green",
    competes: true,
     category: 3
  },
  {
    name: "yellow",
    competes: true,
    category: 4
  }
]

Source: JavaSript – Stack Overflow

November 17, 2021
Category : News
Tags: arrays | if-statement | javascript | loops | sorting

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.