skip to Main Content

I’d like the program to scan through the words, or the innerHTML in the boxes, count how many times each types of color appeared in the boxes, and show the counting results below the table on the screen. I’d like to ask if there is a reduced version for my if functions at the bottom of my Javascript codes, let’s say some multiple for loops, that scans through all the color array, for all the 6 boxes?

const red = ['red', 'carmine', 'crimson', 'scarlet'];
const yellow = ['butter', 'golden', 'corn', 'fire'];
const blue = ['cobalt', 'navy', 'teal', 'cerulean'];
const green = ['dark', 'mint', 'kelly', 'hunter'];
const black = ['ebony', 'charcoal', 'ink', 'metal'];

const b1 = document.getElementById('b1');
const b2 = document.getElementById('b2');
const b3 = document.getElementById('b3');
const b4 = document.getElementById('b4');
const b5 = document.getElementById('b5');
const b6 = document.getElementById('b6');
const count = document.getElementById('count');

var redCount = 0;
var yellowCount = 0;
var blueCount = 0;
var greenCount = 0;
var blackCount = 0;

var box1 = 'scarlet';
var box2 = 'ebony';
var box3 = 'cerulean';
var box4 = 'ink';
var box5 = 'navy';
var box6 = 'charcoal';

b1.innerHTML += box1;
b2.innerHTML += box2;
b3.innerHTML += box3;
b4.innerHTML += box4;
b5.innerHTML += box5;
b6.innerHTML += box6;

if (red.includes(box1) == true) {
  redCount++;
} else if (yellow.includes(box1) == true) {
  yellowCount++;
} else if (blue.includes(box1) == true) {
  blueCount++;
} else if (green.includes(box1) == true) {
  greenCount++;
} else if (black.includes(box1) == true) {
  blackCount++;
}

if (red.includes(box2) == true) {
  redCount++;
} else if (yellow.includes(box2) == true) {
  yellowCount++;
} else if (blue.includes(box2) == true) {
  blueCount++;
} else if (green.includes(box2) == true) {
  greenCount++;
} else if (black.includes(box2) == true) {
  blackCount++;
}

if (red.includes(box3) == true) {
  redCount++;
} else if (yellow.includes(box3) == true) {
  yellowCount++;
} else if (blue.includes(box3) == true) {
  blueCount++;
} else if (green.includes(box3) == true) {
  greenCount++;
} else if (black.includes(box3) == true) {
  blackCount++;
}

/* omitting if functions from (box4) to (box6) */

count.innerHTML += redCount + " " + yellowCount + " " + blueCount + " " + greenCount + " " + blackCount;
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: system-ui, sans-serif;
  color: black;
  background-color: white;
  font-size: large;
}

table {
  border-collapse: collapse;
  border: 2px solid rgb(140, 140, 140);
}

th, td {
  border: 1px solid rgb(160, 160, 160);
}
<table>
  <tbody>
    <tr>
      <td id="b1"></td>
      <td id="b3"></td>
      <td id="b5"></td>
    </tr>
    <tr>
      <td id="b2"></td>
      <td id="b4"></td>
      <td id="b6"></td>
    </tr>
  </tbody>
</table>
<p id="count"></p>

2

Answers


  1. You mean something like this?

    const colors = {
      red: ['red', 'carmine', 'crimson', 'scarlet'],
      yellow: ['butter', 'golden', 'corn', 'fire'],
      blue: ['cobalt', 'navy', 'teal', 'cerulean'],
      green: ['dark', 'mint', 'kelly', 'hunter'],
      black: ['ebony', 'charcoal', 'ink', 'metal']
    };
    
    const boxes = document.querySelectorAll('table tbody td')
    // Initialize the count object
    const count = {
      red: 0,
      yellow: 0,
      blue: 0,
      green: 0,
      black: 0
    };
    
    // Function to increment the count based on color
    const incrementColorCount = color => {
      Object.keys(colors).forEach(key => {
        if (colors[key].includes(color)) {
          count[key]++;
        }
      });
    };
    
    // Iterate through each box and update the count
    boxes.forEach(box => incrementColorCount(box.textContent)); 
    
    // The above will be more complex if more than one word in the cell
    // We can fix that by gathering all colors from all cells into a single array
    // (Adjust the split method based on the actual separator)
    // const allColors = Array.from(boxes).reduce((acc, box) => (acc.concat(box.textContent.split(' '))), []);
    // Iterate through the array of all colors and update the count
    // allColors.forEach(color => incrementColorCount(color));
    
    // show the result
    document.getElementById('count').innerHTML = Object.entries(count).map(([key,value]) => `${key}: ${value}`).join(', ');
    * {
      box-sizing: border-box;
    }
    
    body {
      margin: 0;
      font-family: system-ui, sans-serif;
      color: black;
      background-color: white;
      font-size: large;
    }
    
    table {
      border-collapse: collapse;
      border: 2px solid rgb(140, 140, 140);
    }
    
    th, td {
      border: 1px solid rgb(160, 160, 160);
    }
    <table>
      <tbody>
        <tr>
          <td id="b1">scarlet</td>
          <td id="b3">navy</td>
          <td id="b5">teal</td>
        </tr>
        <tr>
          <td id="b2">charcoal</td>
          <td id="b4">ink</td>
          <td id="b6">corn</td>
        </tr>
      </tbody>
    </table>
    <p id="count"></p>
    Login or Signup to reply.
  2. The answer provided as of right now would be the best as it utilizes querySelectorAll to select all the needed elements. However if you have multiple elements with their IDs scattered in the HTML, you can use something like this for the javascript:

    const colors = {
      red: {
        variants: ["red", "carmine", "crimson", "scarlet"],
        count: 0,
      },
      yellow: {
        variants: ["butter", "golden", "corn", "fire"],
        count: 0,
      },
      blue: {
        variants: ["cobalt", "navy", "teal", "cerulean"],
        count: 0,
      },
      green: {
        variants: ["dark", "mint", "kelly", "hunter"],
        count: 0,
      },
      black: {
        variants: ["ebony", "charcoal", "ink", "metal"],
        count: 0,
      },
    };
    
    const boxes = ["scarlet", "ebony", "cerulean", "ink", "navy", "charcoal"].map(
      (color, idx) => {
        return { HTMLEl: document.getElementById(`b${idx + 1}`), color };
      }
    );
    
    for (const box of boxes) {
      box.HTMLEl.innerHTML += box.color;
    
      for (const color in colors) {
        if (colors[color].variants.includes(box.color)) {
          ++colors[color].count;
        }
      }
    }
    
    document.getElementById("count").innerHTML += Object.values(colors)
      .map((color) => color.count)
      .join(" ");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search