2D arrays Flashcards

1
Q

There are pairs of Nike shoes in size: [ 8 ]
There are pairs of Adidas shoes in size: [ 9 ]
There are pairs of Reebok shoes in size: [ 10 ]
There are pairs of Puma shoes in size: [ 11 ]

A

let shoes = [ [‘Nike’, ‘left’, 8],
[‘Adidas’, ‘right’, 9],
[‘Reebok’, ‘left’, 10],
[‘Puma’, ‘right’, 11],
];

let result = {};

for (let i = 0; i < shoes.length; i++) {
let [brand, side, size] = shoes[i];
if (!result[brand]) {
result[brand] = {
left: [],
right: [],
};
}
result[brand][side].push(size);
}

for (let brand in result) {
if (result[brand].left.length !== result[brand].right.length) {
console.log(There are no pairs of ${brand} shoes);
} else {
console.log(There are pairs of ${brand} shoes in size:, result[brand].left);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

This code first creates an object pairs to store the count of each size of shoes, where the size is the key and the value is an array [left, right] representing the count of left and right shoes of that size.

Next, it loops through shoes and adds to the count of left or right shoes for each size.

Then, it loops through pairs and checks if the count of left and right shoes are equal for each size. If not, it adds a string representing the unpaired shoes to unpairedShoes array.

Finally, it logs the result: either “All shoes have pairs” or “Unpaired shoes: …” with a list of unpaired shoes.

A

let shoes = [[0, 9.5], [1, 9.5], [0, 8.5], [1, 8.5], [0, 10]];
let pairs = {};

for (let i = 0; i < shoes.length; i++) {
let shoe = shoes[i];
let type = shoe[0];
let size = shoe[1];
if (!pairs[size]) {
pairs[size] = [0, 0];
}
pairs[size][type]++;
}

let unpairedShoes = [];

for (let size in pairs) {
let left = pairs[size][0];
let right = pairs[size][1];
if (left !== right) {
unpairedShoes.push(${left} left shoe(s) and ${right} right shoe(s) of size ${size});
} else {
console.log(There are ${left} pairs of size ${size});
}
}

if (unpairedShoes.length > 0) {
console.log(“Unpaired shoes: “ + unpairedShoes.join(‘, ‘));
} else {
console.log(“All shoes have pairs”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly