I need to separate the data from an Array depending on the player-id. The database I've got looks like this:
var database =[
{
player: 1,
level: 1,
score: 20
},
{
player: 2,
level: 1,
score: 25
},
{
player: 3,
level: 1,
score: 7
},
{
player: 1,
level: 2,
score: 25
},
{
player: 2,
level: 2,
score: 7
}
]
Little by little, new objects containing new players will be added and old objects will disappear, as the database is limited to 40 entries. This means that the database changes dynamically.
My goal is to push the objects into new Arrays depending on the player-id. So the result has to look like this:
var player1 = [
{
player: 1,
level: 1,
score: 20
},
{
player: 1,
level: 2,
score: 25
}
]
var player2 = [
{
player: 2,
level: 1,
score: 25
},
{
player: 2,
level: 2,
score: 7
}
]
var player3 = [
{
player: 3,
level: 1,
score: 7
}
]
CodePudding user response:
First, you can convert the array to an object to improve the access and then you can assign object properties to variables:
const database = [
{
player: 1,
level: 1,
score: 20
},
{
player: 2,
level: 1,
score: 25
},
{
player: 3,
level: 1,
score: 7
},
{
player: 1,
level: 2,
score: 25
},
{
player: 2,
level: 2,
score: 7
}
];
const { player1, player2, player3 } = database.reduce((acc, el) => {
if (!('player' el.player in acc)) acc['player' el.player] = [el];
else acc['player' el.player].push(el);
return acc
}, {});
console.log(player1, player2, player3);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Although it's possible to create global variables with dynamic names, it's not possible to create non-global variables with dynamic names, and the global environment is already sufficiently crowded that creating a bunch of new globals is not best practice.
Instead, use a Map
:
const playerArrays = new Map();
for (const entry of database) {
const key = `player${entry.player}`;
const array = playerArrays.get(key);
if (!array ) {
// Haven't seen this one yet, add a new array
playerArrays.set(key, [entry]);
} else {
// We have the array, add to it
array.push(entry);
}
}
Then you get an individual array by using playerArrays.get("player1")
and such.
Live Example:
var database = [{
player: 1,
level: 1,
score: 20
},
{
player: 2,
level: 1,
score: 25
},
{
player: 3,
level: 1,
score: 7
},
{
player: 1,
level: 2,
score: 25
},
{
player: 2,
level: 2,
score: 7
}
];
const playerArrays = new Map();
for (const entry of database) {
const key = `player${entry.player}`;
const array = playerArrays.get(key);
if (!array ) {
// Haven't seen this one yet, add a new array
playerArrays.set(key, [entry]);
} else {
// We have the array, add to it
array.push(entry);
}
}
console.log("player1:", playerArrays.get("player1"));
.as-console-wrapper {
max-height: 100% !important;
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>