How to add a specific key to an array object?

Asked

Viewed 65 times

-1

I’m starting in Javascript and have the following problem:

Given the array:


const game = [['John', 'rock'], ['Mayk', 'scissors']];

I need to verify who is the winner (of a jokempô tournament), IE, need to compare the elements of the array.

For this, I thought of turning the array into an object.

So I created

const keys = [['name', 'play']];

And I concatenated both vectors as follows:

Array.prototype.push.apply(keys, game);

Then I tried to transform this new array into an object like this:

function arrayToObject(array) {
    const keys = [['name', 'play']];
    let result = {};
    Array.prototype.push.apply(keys, array);
    for (const element of keys) { 
        result[element[0]] = element[1];
    }
    return result;
}

And obviously, by printing this, it gave

{ name: 'play', John: 'rock', Mayk : 'scissors' }

I need to invert the columns with the rows, put the keys as "name" and "play".

Is there a function for such? Or some other simpler suggestion?

  • Hi, Laura. I don’t quite understand which "structure" you want to create. Could [Dit] your question to try to detail a little better?

  • I edited it, but I don’t know if it’s clear yet. Basically I wanted to put the keys as "name" and "play", and not the first element of each vector as keys (as it is printing)

  • Do you have to follow this path? I ask because I find it very complicated for something so simple that it can be solved in two lines of code.

  • What should be the result? Do you just want to check who won? If so, you don’t need to build the object

  • If it’s just to check who won: https://ideone.com/wDNVz4

1 answer

0

You can do it this way:

Read Stone, paper and scissors for rules.

We can create a rulesObject:

const rules = {
  "rock paper": "paper",
  "paper rock": "paper",
  "rock scissors": "rock",
  "scissors rock": "rock",
  "scissors paper": "scissors",
  "paper scissors": "scissors",
};

We can use it to find the winner:

function findWinner(game) {
  const win = rules[game[0][1] + " " + game[1][1]];
  const winner = game.find((item) => item[1] === win);
  return winner;
}

An example:

function findWinner(game) {
  const win = rules[game[0][1] + " " + game[1][1]];
  const winner = game.find((item) => item[1] === win);
  return winner;
}

const rules = {
  "rock paper": "paper",
  "paper rock": "paper",
  "rock scissors": "rock",
  "scissors rock": "rock",
  "scissors paper": "scissors",
  "paper scissors": "scissors",
};


let game = [
  ["Player1", "rock"],
  ["Player2", "paper"],
];
console.log(findWinner(game));

game = [
  ["John", "rock"],
  ["Mayk", "scissors"],
];
console.log(findWinner(game));

game = [
  ["John", "scissors"],
  ["Mayk", "paper"],
];
console.log(findWinner(game));

game = [
  ["John", "paper"],
  ["Mayk", "scissors"],
];
console.log(findWinner(game));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.