I am trying to build something like card memory game and I am populating cards with font awesome icons. But I already encountered a problem as I often get empty pair instead of pair of icons. This is one example of my array shown in the console: Array(16) 0: ['github'] 1: [] 2: ['opera'] 3: ['opera'] 4: [] 5: ['reddit'] 6: ['xbox'] 7: ['github'] 8: ['java'] 9: ['reddit'] 10: ['xbox'] 11: ['docker'] 12: ['java'] 13: ['redhat'] 14: ['docker'] 15: ['redhat']
And this is my JS code:
let brands = [
"angular",
"amazon",
"apple",
"css3",
"docker",
"edge",
"dropbox",
"elementor",
"ethereum",
"figma",
"github",
"gitlab",
"gulp",
"hackerrank",
"html5",
"java",
"js",
"kaggle",
"laravel",
"linkedin",
"linux",
"mailchimp",
"medium",
"microsoft",
"opencart",
"opera",
"paypal",
"pinterest",
"python",
"quora",
"react",
"reddit",
"redhat",
"rust",
"safari",
"skype",
"slack",
"snapchat",
"spotify",
"swift",
"tiktok",
"telegram",
"twitter",
"unity",
"unsplash",
"vuejs",
"wordpress",
"xbox",
"xing",
"yarn",
];
let brandsCopy = brands.slice();
const easyBtn = document.querySelector(".easy");
const mediumBtn = document.querySelector(".medium");
const hardBtn = document.querySelector(".hard");
const expertBtn = document.querySelector(".expert");
const container = document.querySelector(".container");
let selectedBrands = [];
function createTable(n) {
container.innerHTML = "";
selectedBrands = [];
randomLogos(n);
let icon;
for (let i = 0; i < n * n; i++) {
let img1 = document.createElement("div");
img1.classList.add("cool");
for (let j = 0; j < n; j++) {
icon = document.createElement("i");
icon.classList.add("fab");
icon.classList.add("fa-" + selectedBrands[i]);
}
img1.appendChild(icon);
container.appendChild(img1);
}
return;
}
function randomLogos(n) {
for (let i = 0; i < (n * n) / 2; i++) {
let randomBrand = brandsCopy.splice(
Math.floor(Math.random() * brands.length),
1
);
selectedBrands.push(randomBrand);
selectedBrands.push(randomBrand);
}
selectedBrands = selectedBrands.sort(() => Math.random() - 0.5);
console.log(selectedBrands);
brandsCopy = brands.slice();
return selectedBrands;
}
console.log(brands);
codepen: https://codepen.io/argentinaivan/pen/YzEVeGp
What am I doing wrong here?