You can keep track of the 2 min values in your for loop. You will also need to keep track of the ids that correspond to those min values. You can see a working snippet here below:
var passengers = document.querySelectorAll(".car");
var trainCar = {};
let min = Infinity;
let min2 = Infinity;
let minId, min2Id;
for (let i = 0; i <= passengers.length-1; i++) {
const value = Math.floor(Math.random() * 100);
if(value < min){
min2 = min;
min2Id = minId;
min = value;
minId = i;
} else if (value < min2){
min2 = value;
min2Id = i;
}
passengers[i].innerHTML = value;
trainCar[i] = {
numberOfPassengers: value,
carId: passengers[i].id,
}
}
passengers[minId].style.backgroundColor = 'grey';
passengers[min2Id].style.backgroundColor = 'grey';
<div class="train">
<div class="car" id = "car1">a</div>
<div class="car" id = "car2">b</div>
<div class="car" id = "car3">b</div>
<div class="car" id = "car4">b</div>
<div class="car" id = "car5">b</div>
<div class="car" id = "car6">b</div>
</div>
First of all, I apologize if this is a stupid question, I’m fairly new to JavaScript and have been experimenting and trying to do this for several days now.
Let’s say I have 6 train cars (divs) with their respective id’s.
<div class="train">
<div class="car" id = "car1">a</div>
<div class="car" id = "car2">b</div>
<div class="car" id = "car3">b</div>
<div class="car" id = "car4">b</div>
<div class="car" id = "car5">b</div>
<div class="car" id = "car6">b</div>
</div>
My script generates innerText of these divs using random numbers from 0 to 160 (number of passengers in each respective train car).
I want to change the background color of 2 cars with the least amount of passengers.
First, I create a new Object of trainCar to contain information about the number of passengers and the car id.
var passengers = document.querySelectorAll(".car");
var trainCar = {};
for (let i = 0; i <= passengers.length-1; i++) {
passengers[i].innerHTML = getRandomNumber();
trainCar[i] = {
numberOfPassengers: passengers[i].innerHTML,
carId: passengers[i].id,
}
}
This creates multiple objects within my main object trainCar (this is the console.log):
{0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}}
0: {numberOfPassengers: "17", carId: "car1"}
1: {numberOfPassengers: "87", carId: "car2"}
2: {numberOfPassengers: "106", carId: "car3"}
3: {numberOfPassengers: "157", carId: "car4"}
4: {numberOfPassengers: "154", carId: "car5"}
5: {numberOfPassengers: "56", carId: "car6"}
So this is where I’m stuck. I can change background color of one of the cars using:
document.getElementById(trainCar[2].carId).style="background-color: grey";
but I have no idea how to match the lowest value of innerHTML with the corresponding id and change this id’s background (let alone the lowest two).
Wow, that worked. I was doing it completely the wrong way 🙂 Thank you for the elegant solution, sir. However, I don’t fully understand the