Creating new arrays each iteration - javascript

I possibly am looking at this incorrectly, but I'm trying to make a tournament bracket creator. You input names that are entered into an Object called players I only want each side of the bracket to have four players in it. So I thought the best course of action would be to find out how many sides i would have in the bracket, once I had that I could look over those sides and for each loop I could place players in those sides but I've run into a bit of a problem. I'm not sure how to dynamically create these sides each pass. I removed some of my bad code so you can see kind of the idea I have
const players = []
function Player(name, deck){
this.name = name
this.deck = deck
this.points = 0
this.id = players.length + 1
}
function addPlayer(){
let player = new Player (
document.getElementById('name').value,
document.getElementById('deck').value
)
//console.log(player)
document.getElementById('name').value = ''
document.getElementById('deck').value = ''
players.push(player)
logPlayers()
}
function logPlayers (){
output = ''
for (let index = 0; index < players.length; index++) {
output += (index + 1) + ') ' + players[index].name + ' | ' + players[index].deck + '<br>'
}
document.getElementById('output').innerHTML = output
}
function initGame(){
game = ''
let cube = []
const four = Math.floor(players.length/4)
//console.log(four)
const remainder = four % 1
for (let index = 0; index < four; index++) {
for (let j = 0; j < 4; j++) {
}
}
}
My array cube is what I was gonna uses as my sides and four is how many of those sides I will have. I will loop over them, and inside that loop I'll ensure I only put 4 players into each, however I'm getting confused on how I will create different cubes each pass.
I hope I explained this correctly

let cube = []
const four = Math.ceil(players.length/4)
let playerIndex = 0;
for (let index = 0; index < four; index++) {
for (let j = 0; j < 4; j++) {
if (!cube[index]) {
cube[index] = [];
}
cube[index].push(player[playerIndex])
playerIndex++
}
}
This could be what you want?
player[playerIndex] will be the individual player by their array index, assuming player is an array containing the players.

Related

How to get next element in for loop in javascript

In a dataset I have different locators. Some places are free (locator = null). I would like to capture these and push them into arrays.
In the subarray may only be locations that are in a row. If a distance is greater than 1 then it comes to the next array.
const freeLocs = locs.filter(elem => !elem.locator)
let temp = []
let array2D = []
for(let i = 0; i < freeLocs.length-1; i++) {
let abs = Math.abs(freeLocs[i+1].position - freeLocs[i].position)
temp.push(freeLocs[i])
if(abs > 1) {
array2D.push(temp)
temp = []
}
}
console.log(array2D)
Now I have the problem that the last array is not filled.
https://jsfiddle.net/5yk0mpt9/2/
Problem starts here:
for(let i = 0; i < freeLocs.length-1; i++) {
with this condition you lose the last item of the array:
i < freeLocs.length-1
it needs to change like this:
i < freeLocs.length
but it also needs an extra check inside the loop before trying to get the
freeLocs[i + 1].position
for the last iteration
for example:
for (let i = 0; i < freeLocs.length; i++) {
temp.push(freeLocs[i]);
if (
(i === freeLocs.length - 1) ||
(Math.abs(freeLocs[i + 1].position - freeLocs[i].position) > 1)
) {
array2D.push(temp)
temp = [];
}
}
working demo here: DEMO

How can I use Javascript to iterate twice over an array element?

Please help! I need to declare an empty array (foodTray = []), and run a loop 5x (for each iteration push a food type), the foodTray has to hold a max of 2 types but the total length should not exceed 5.
const foodTypes = ['seafood', 'nuts', 'seeds'];
I had done this =>
'use strict';
let foodTray = [];
const foodTypes = ['seafood', 'nuts', 'seeds'];
for (let x = 0; x < foodTypes.length; x++) {
const food = foodTypes[x];
foodTray.push(food);
if (foodTray.length < 5) {
foodTray.push(food);
}
}
console.log('I have ' + `${foodTray}.`);
but I was instructed the loop had to run 5 times***** and what I used was the length of the foodTypes.
The desired output should be => I have seafood, seafood, nuts, nuts, seeds.
The problem: I did for (let x = 0; x < *foodTypes.length*; x++)
instead, the loop should run 5 times! I am not sure how I can iterate twice over an element.
Your original code is giving you the desired output which is : I have seafood, seafood, nuts, nuts, seeds.
let foodTray = [];
const foodTypes = ['seafood', 'nuts', 'seeds'];
for (let x = 0; x < foodTypes.length; x++) {
const food = foodTypes[x];
foodTray.push(food);
if (foodTray.length < 5) {
foodTray.push(food);
}
}
console.log('I have ' + `${foodTray}.`);

How to improve the performance of 'for loop' to integrate some objects in JS

I have three for loop as below to integrate their objects.
The problem is the length of 'cars' array is 20,000.
So it should runs every 20,000 times for finding same id between company.user and cars.
But the id of cars is unique.
Can I reduce this repeat number in JS?
I want to reduce the taking time.
Thank you for reading it.
p.s. I uploaded same question adding the concrete logic inside of for loop.
for (let i = 0; i < company.length; i += 1) {
for (let j = 0; j < company[i].user.length; j += 1) {
for (let k = 0; k < cars.length; k += 1) {
if (company[i].user[j].id === cars[k].id) {
company[i].user[j] = {
...company[i].user[j],
...cars[k]
}
}
}
}
}
If there is only 1 match then use break after you found that item. Imagine you find that item at index 1 for example, then the loop would still continue and do 19998 loops. Because of the information that you know there is only 1 possible match you can break it there.
if (company[i].user[j].id === cars[k].id) {
company[i].user[j] = {
...company[i].user[j],
...cars[k]
}
break;
}
for (let i = 0, leni = company.length;; i < leni ; i += 1) {
for (let j = 0, lenj = company[i].user.length; j < lenj; j += 1) {
for (let k = 0, lenk = cars.length; k < lenk; k += 1) {
if (company[i].user[j].id === cars[k].id) {
company[i].user[j] = {
...company[i].user[j],
...cars[k]
}
break; // match only the first one, then stop searching for cars
}
}
}
}
Answer based on test results from https://jsperf.com/caching-array-length/4
Spread left in base on
https://thecodebarbarian.com/object-assign-vs-object-spread.html
this will optimize your code a little more, but ziga1337 is right, the only effective way is to sort your two objects
// company: [ { user: [ { id: '?1'
// cars: [ { id: '?2'
for (let iCompagny of compagny) {
for (let iUser of iCompagny.user) {
let fCar = cars.find(xCar.id===iUser.id)
if (fCar) Object.assign(iUser, fCar)
}
}
in case there is always a car.id unique to each user.id:
let indexCars = cars.reduce((a,c)=>{ a[c.id]=c; return a },{})
compagny.forEach(iCompagny=>{
iCompagny.user.forEach(iUser=>{ Object.assign(iUser, indexCars[iUser.id]) })
})

How to update a multi-dimensional array with an object on a boardgame

I'm trying to make a boardgame using oop in javascript. (very new to oop).
The idea is to have a multi-dimensional array with objects represented by a value or id.
I have made a multi-dimensional array to be the board.
I have created an object for the players as an example.
I can't seem to find a way to:
add the player (and other objects) to the board itself
add the player (and other objects) in a random spot on the board
createPlayers() {
for (let i = 0; i < players; i++) {
let players = [new Player("Player 1", 1),
new Player("Player 2", 2)
];
players.push(m);
}
}
I've tried using push() in a for loop but I'm not sure if this is correct or anywhere close.
this is what i have that works:
class Board {
constructor(rows, cols) {
let Board = [];
for (let i = 0; i < rows; i++) {
Board[i] = [];
for (let j = 0; j < cols; j++) {
Board[i][j] = 0;
}
}
return Board
}
}
let m = new Board(10, 10);
class Player {
constructor(name, id) {
this.name = name;
this.id = id;
}
}
let players = [new Player("Player 1", 1),
new Player("Player 2", 2)
];
I get this far - no problem, when I console.table(m) the array shows with 0 as the default
The aim is to have the object (player) represented in the array as the number 1 and 2 and in a random spot.
I can get a random 1's to appear using
board[i][j] = (Math.random() * 2 | 0) + 0;
in the for loop for the board. but this is fairly useless at this stage as I can't seem to work out how to update the array.
any suggestions will be appreciated!
class Board {
constructor(rows, cols) {
let Board = [];
for (let i = 0; i < rows; i++) {
Board[i] = [];
for (let j = 0; j < cols; j++) {
Board[i][j] = 0;
}
}
return Board
}
}
let totalRows = 10;
let totalCols = 10;
let m = new Board(totalRows, totalCols);
class Player {
constructor(name, id) {
this.name = name;
this.id = id;
}
}
let players = [
new Player("Player 1", 1),
new Player("Player 2", 2)
];
players.forEach(function(player){
let row, col, notInserted = true;
while (notInserted) {
row = Math.floor(Math.random() * 100) % totalRows;
col = Math.floor(Math.random() * 100) % totalCols;
if (m[row][col] === 0) {
m[row][col] = player.id;
notInserted = false;
}
}
});
console.log(m);
Once you have created the board and the players, loop over each player. For each player, get a random row and column number inside the boundary of the board. If that position on the board is 0, set the player there. If it is not 0, repeat the random number logic to get another position and continue until one is found that is 0.

For loop condition issues

I am having troubles figuring out the for condition for a javascript learning course I am doing.
I am not getting normal errors because I am doing it in the course, but the error I am receiving in the course is this...
Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.
These are the instructions:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
for(var i = 0; // rest of loop setup
your second should be something like
for(var j = i; // rest of loop setup
Second, think hard about when your loop should stop. Check the Hint if you get stuck!
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
This is my code
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; i < myName.length; i++) {
hits.push();
}
}
}
I know the issue resides in this line:
for (var j = i; i < myName.length; i++) {
I just can't figure out exactly how I need to structure it.
UPDATE:
Final answer of question:
/*jshint multistr:true */
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; j < (i + myName.length); j++) {
hits.push(myName);
}
}
}
if (hits === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
I'll give you the solution because you can learn more from the direct solution than from banging your head on that one.
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var equal = true;
for (var j = 0; j < myName.length; j++) {
if (text[i + j] != myName[j]) {
equal = false;
break;
}
}
if(equal) hits.push(myName);
}
}
There may be other ways to reach this result. This is one of them.
Explaing what "push" does:
Arrays are lists of variables. You store a value in a variable like this:
var myNumber = 777;
var myName = "Nelson";
An array declaration looks like this:
var myNumbers = [];
then you put something inside of it, like this:
myNumbers.push(333);
myNumbers.push(555);
myNumbers.push(777);
then if you try: console.log(myNumbers), it will print: [333, 555, 777]
if you add another push:
myNumbers.push(999);
will add 999 to the list resulting in [333, 555, 777, 999]
Check this demo
got it ? take a look here to more detailed explanation:
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Am not sure what you are trying to achieve,
Here is something may help
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var res = '';
for (var j = i; j < i+myName.length; j++) {
res = res+text[j];
}
if(res == myName)
{
hits.push(myName);
}
}
}
console.log(hits);
Here is demo

Categories

Resources