Problem
I have a 2D array matches
where I store the game id and another array of objects games
where I store gameId
with the playerId
.
Here is what I have done so far:
Step 1: I get the opponent’s gameId against the gameId from “matches” array.
e.g. gameId “2” has an opponent “1”
Step 2: check opponent_game in games and return game.
let gameId = 2
let matches = [
[1, 2],
[3, 4]
]
const opponent_game = matches.filter((v, i) => {
if (v.includes(gameId)) {
var index = v.indexOf(gameId);
if (index > -1) {
return v.splice(index, 1);
}
}
})
let games = [{
gameId: 1,
playerId: 222
}, {
gameId: 4,
playerId: 222
}]
const game = games.filter((v, i) => {
return v.gameId === opponent_game[0][0]
})
console.log(game)
Please suggest best practices in javascript or an optimized and clean way to write the same solution. TIA
Solution
.includes()
and checking .indexOf()
against -1
do the same thing, you only need one.
Also the function should be returning a boolean value. It currently works because the array returned by .splice()
is considered true
and not returning anything (or undefined
) is considered false
. It would be better to explicitly return a boolean:
const opponent_game = matches.filter((v, i) => {
var index = v.indexOf(gameId);
if (index > -1) {
v.splice(index, 1);
return true;
}
return false;
})
However modifying the content of an array in a filter
is bad practice, because it is unexpected. Since you only looking for a single value .reduce()
would probably be the better choice:
const opponent_game = matches.reduce((acc, v) => {
if (acc !== null) {
return acc;
}
var index = v.indexOf(gameId);
if (index > -1) {
return v[1 - index];
}
return null;
}, null)
In this case opponent_game
is a number and no longer an array containing an array containing a number so that simplifies the second part too. Also since you are looking for a single item .find()
would be more appropriate:
const game = games.find(v => {
return v.gameId === opponent_game
})