-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?
– Luiz Felipe
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)
– Laura
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.
– Augusto Vasques
What should be the result? Do you just want to check who won? If so, you don’t need to build the object
– hkotsubo
If it’s just to check who won: https://ideone.com/wDNVz4
– hkotsubo