'can't look up key value using value from array

I'm coding a game with 100 tiles that are generated like this:

const allLetters = {
  'A': { 'points':  1, 'tiles':  9 },
  'B': { 'points':  3, 'tiles':  2 },
  'C': { 'points':  3, 'tiles':  2 },
  'D': { 'points':  2, 'tiles':  4 },
  'E': { 'points':  1, 'tiles': 12 },
  'F': { 'points':  4, 'tiles':  2 },
  'G': { 'points':  2, 'tiles':  3 },
  'H': { 'points':  4, 'tiles':  2 },
  'I': { 'points':  1, 'tiles':  9 },
  'J': { 'points':  8, 'tiles':  1 },
  'K': { 'points':  5, 'tiles':  1 },
  'L': { 'points':  1, 'tiles':  4 },
  'M': { 'points':  3, 'tiles':  2 },
  'N': { 'points':  1, 'tiles':  6 },
  'O': { 'points':  1, 'tiles':  8 },
  'P': { 'points':  3, 'tiles':  2 },
  'Q': { 'points': 10, 'tiles':  1 },
  'R': { 'points':  1, 'tiles':  6 },
  'S': { 'points':  1, 'tiles':  4 },
  'T': { 'points':  1, 'tiles':  6 },
  'U': { 'points':  1, 'tiles':  4 },
  'V': { 'points':  4, 'tiles':  2 },
  'W': { 'points':  4, 'tiles':  2 },
  'X': { 'points':  8, 'tiles':  1 },
  'Y': { 'points':  4, 'tiles':  2 },
  'Z': { 'points': 10, 'tiles':  1 },
  ' ': { 'tiles': 2 }
}

let tiles = [];

Object.keys(allLetters).forEach(letter => {
  for (let i = 0; i < allLetters[letter]['tiles']; i += 1){
    tiles.push(letter);
  }
});

console.log(tiles);

I want to associate each tile with a point value, so this is what I tried:

var playersTiles = [];
for (let i = 0; i < 7; i++){
  let tileIndex = Math.round(Math.random() * (tiles.length - 1));
  playersTiles.push(tiles[tileIndex]);
  let letter = playersTiles[i];
  let points = allLetters[letter]['points'];
  playersTiles.push(tiles[tileIndex][points]);
  tiles.splice(tileIndex, 1);
}

My code returns an error on this line:

let points = allLetters[letter]['points'];

It says:

allLetters[letter] is undefined

What am I doing wrong?



Solution 1:[1]

That's because tiles is a one dimensional array shown in your code here

let tiles = [];

Object.keys(allLetters).forEach(letter => {
    for (let i = 0; i < allLetters[letter]['tiles']; i += 1){
        tiles.push(letter); // Pushing only the letter which makes it one-dimensional array
    }
});

And in this part playersTiles.push(tiles[tileIndex][points]); you are assuming that tiles is a two-dimensional array

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rhemmuuu