javascript: array with unknown length and unknown index names - javascript

I am making a program of a football league.
A example of a league:
team1
team2
team3
I want to save (increase) number of players for each team like
var teamArray = [];
teamArray[team1] = 1;
teamArray[team2] = 2;
and I am doing in the body of some functions like:
function 1(){}
function 2(){}
function .(){}
function .(){}
function .(){}
function n(){}
but this works only when i "teach" javscript that the array is an integer array... with somethin like
teamArray[team1] = 0;
teamArray[team1] = teamArray[team1] + 1;
but the problem is every time when i come to one of my functions, i have to set my array element to 0 and that makes the whole calculation wrong...
Could anyone give me a hint please?
My Idea was to was to set each array element to 0 from the beginning, but i dont know at the beginning of my game how many teams i will have today, that why i implemented the array like:
var teamArray = [];

Use a JavaScript object instead. Something like:
var teamObject = {
team1: 3,
team2: 5,
team3: 7,
};
Or, perhaps an array of objects:
var teamArray = [
{ name: 'team1', players: 3 },
{ name: 'team2', players: 5 },
{ name: 'team3', players: 7 }
];
The object is easier to access if all you want is to get or set the number of players:
teamObject.team1 += 1;
but an array is easier to loop through and can be ordered:
for (var i=0,j=teamArray.length; i<j; i++) {
console.log(teamArray[i].name + " has " + teamArray[i].players + " players");
}

You can increment the number of team members by testing the current number first, and if it does not exist, you initialise it with 0 on the fly. All that can be done in one expression with a logical OR (||):
teamArray[team1] = (teamArray[team1] || 0) + 1;
This will not destroy the previous value you had and work like a simple + 1 in that case.
You should define your teamArray as object, although it will work with array as well (since that is an object as well):
teamArray = {}
The name is then of course a bit confusing, but I'll stick with it.
Whenever you need to iterate over the teams you have collected, then you can use a for loop like this:
for (var team in teamArray) {
console.log(team, teamArray[team]);
}

thanks for all your help!
I did it like this now:
var listItems = $("#teamsDropdown li");
listItems.each(function(idx, li) {
var team = $(li).text();
TeamPlayerQuantities[team] = 0;
});
and increasing the qnty of players wiht functions like:
function1(team){
TeamPlayerQuantities[team] ++;
}

Related

how can I filter an array without losing the index?

I have two really long arrays containing "picture names" and "picture files". The first one represents the actual name of the pictures, while the second one is just the file name. For example:
picturenames[0] = '0 - zero';
picturenames[1] = '1 - one';
picturenames[2] = '1 o\'clock';
...
picturefiles[0] = 'numbers-zero.jpg';
picturefiles[1] = 'numbers-one.jpg';
picturefiles[2] = 'time-1.jpg';
...
I have about 1000 items in each array in several languages (the picture files are always the same). I'm "recycling" these arrays from the previous application to save some time and avoid rewriting everything anew.
Desirable functionality: using the user's input in a textbox I want to filter the picturenames array and then show the correspondant picturefiles image.
The issue I'm facing: when I filter the picturenames array I lose the index and I can't "reach" the picture file name.
This is the code I'm using to filter the picturenames array.
var matches = picturenames.filter(function(windowValue){
if(windowValue) {
return windowValue.indexOf(textToFindLower) >= 0;
}
});
What would be the best way to do this?
UPDATE: the solution proposed by Ahmed is the best one, but for time reasons and negligible performance issues I'm just using a for loop to search trough the array, as follows:
var matchesCounter = new Array();
for (i = 0; i < picturenames.length; i++) {
if (picturenames[i].indexOf(textToFindLower) >= 0) {
matchesCounter.push(i);
}
}
console.log(matchesCounter);
for (i = 0; i < matchesCounter.length; i++) {
console.log(picturenames[i]);
console.log(picturefiles[i]);
}
Try this:
const foundIndicies = Object.keys(picturenames).filter(pictureName => {
pictureName.includes(textToFindLower)
});
// reference picturefiles[foundIndicies[0]] to get the file name
Though, it would be far nicer to have both the name and the file in a single object, like so:
const pictures = [
{
name: '0 - zero',
file: 'numbers-zero.jpg',
},
{
name: '1 - one',
file: 'numbers-one.jpg',
}
];
const foundPictures = pictures.filter(picture => picture.name.includes('zero'));
if (foundPictures[0]) console.log(foundPictures[0].file);
You can add one property index during the filtering time, then later on you can use the index.
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.comparator(textToFindLower) >= 0;// Need to define comparator function
}
});
Later on you can access by using like follows:
picturefiles[matches[0].index]
However, the solution will work on object, not primitive type string.
If your data type is string, then you have to convert as object and put the string as a property value like name. The snippet is given below:
var picturenames = [];
var picturefiles = [];
picturenames.push({name:'0 - zero'});
picturenames.push({name:'1 - one'});
picturenames.push({name:'1 o\'clock'});
picturefiles.push({name:'numbers-zero.jpg'});
picturefiles.push({name:'numbers-one.jpg'});
picturefiles.push({name: 'time-1.jpg'});
var textToFindLower = "0";
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.name.indexOf(textToFindLower) >= 0;
}
});
console.log(matches);

How to check if data being added to an array already exists in a different array?

I am looking to create a simple script for a Google sheet in which array 1 will already be populated with a list of names. As a new name gets added to array 2, array 1 is checked for the name. If the name which was entered into array 2 is present in array 1 an action will be performed. This search function must take place each time a new name is added to array 2 to determine if it exists in array 1.
function findPlayer() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var picksRange = ss.getRange("B2:M15");
var poolRange = ss.getRange("B21:G96");
var picksPlayerName = picksRange.getValues();
var poolPlayerName = poolRange.getValues();
for (var i = 0; i < picksRange.length; i++)
for (var j = 0; j < poolRange.lenth; j++)
if (picksPlayerName[i] == poolPlayerName[j]) {
poolPlayerName[i].setBackground("red")}
else {
poolPlayerName[j].setBackground("blue");}
}
This is not a complete answer, nor does it perfectly fit your use-case, but you should be able to take it from here, or perhaps come back with another question when you have a question about a specific part of your code.
const existingNames = ["Carl", "Emma", "Sarah", "Ahmad"];
const newNames = ["Emma", "Sarah", "Isa", "Igor", "Kent"];
// go through the new names and check against existing ones
newNames.forEach(newName => {
if(existingNames.includes(newName)) {
// handle duplicates: do nothing?
} else {
// handle new names: maybe add them to the existing names?
existingNames.push(newName);
}
});
console.log('After going through all new names, the complete list of known names are: ' + existingNames);
Demo where you can play with the code and learn: https://jsfiddle.net/jonahe/11uom4cu/

Naming objects inside of an array dynamically

I'm quite new to JavaScript and programming in general and figured I'd hone my abilities by working on a small project. The idea is that I have a form for information on an event, an input for the name, date, time and a small thumbnail image.
I want each event to be an object inside of an array, so I would have something like:
var concerts = {};
for (var i = 1; i < 11; i++) {
window["concert"+i] = new Object();
}
and the array would end up being something:
var concerts = [concert1, concert2, concert3]
and so on.
How could I get this loop to work so that it would take the 3 parameters and create a new object in the array named 'concert'+i? Thanks for reading!
Concerts must be an array:
var concerts = [];
for (var i = 0; i < 10; i++) {
concerts[i] = {
//maybe also giveit a name if you want to:
name:"concert"+i
};
}
You can access it like this:
concerts[0].name="Wacken";//first concert...
Note that this:
window["concert"+i] = new Object();
is very bad style...
First you declare a variable concerts of type object. But you want an array. That first line makes your code very confusing.
You have to start with an empty array:
var concerts = []; // alternatively: new Array();
In the end you'd like to have a structure like this:
[
{ /* object 1 */ },
{ /* object 2 */ }
]
Now you can run a foor-loop and populate the array:
for (var i = 0; i <= 10; i++) {
concerts.push({['concert' + i]: {}});
}
This will return something like:
[
{'concert0': {}},
{'concert1': {}},
// skipped
{'concert10': {}}
]
Later you can populate the objects. This is however not a very nice style. Maybe you should reconsider if it is really necessary to give a name to every object like concert0...10.
Go rather for:
var concerts = [
{
'name': 'concert0',
'location': 'somewhere'
}
// continue with other objects
];

How to create multiple objects based on dynamic data?

Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}

Run through for loop and randomly change values of variable within a range but satisfy all variables

So what I have is a quiz which is generated dynamically. I want the quiz questions to be ordered randomly. Basically, the i is going from 0 to the length of answerArray. I want it to do this, but not in order randomly. For instance: instead of 0,1,2,3,4,5 I want 1,0,2,3,5,4. I have tried doing this but all of my attempts failed. It would be very helpful if I could do this so the test questions would not always be in order. Thank you.
var displayAnswers = function (){
for (var i = 0; i<answerArray.length;i++){
var row1= document.createElement("div");
$(row1).addClass("row");
var colmd= document.createElement("div");
$(colmd).addClass("row");
$(colmd).addClass("text-center");
$(colmd).addClass("rowtxt");
$(colmd).attr('id',"questionTxt"+[i+1]);
$("#contain").append(row1)
$(row1).append(colmd);
var answer = answerArray[i];
}
You can use accepted answer in the following question Generate unique random numbers between 1 and 100, that will generate the random numbers first and store them in array and use them inside for loop.
Example :
var arr = [];
var answerArray = ["Answer 1", "Answer 2", "Answer 3"];
while( arr.length < answerArray.length ){
var randomnumber=Math.ceil( Math.random() * answerArray.length)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
Now you have an array of unique numbers between 0 and answerArray length, you can use it inside the loop just by calling arr[i] :
var displayAnswers = function (){
for (var i = 0; i<answerArray.length;i++){
var row1= document.createElement("div");
$(row1).addClass("row");
var colmd= document.createElement("div");
$(colmd).addClass("row");
$(colmd).addClass("text-center");
$(colmd).addClass("rowtxt");
$(colmd).attr('id',"questionTxt"+[i+1]);
$("#contain").append(row1)
$(row1).append(colmd);
//Here you get the unique number between 0 and answers length
var random_number = arr[i];
var answer = answerArray[random_number];
}
}
Hope this helps.
I would start by thinking about what you need to do.
You want to track what numbers you have used already and getting a new number if you have already used the one generated.
Try something like this.
// The initial array
var Array = [1,2,3,4,5];
// The new array or tracking array
var Used = [];
// A function to generate the random index
// We need a function so we can call it if
// the index already exists to ensure we have
// the same amount of values as the inital
// array
function addRandomNum(array) {
var random = Math.floor((Math.random() * Array.length) + 1);
if(array.indexOf(random) === -1){
array.push(random);
} else {
addRandomNum(array);
}
};
// Loop the inital array calling the function
for(var i = 0; i < Array.length; i++){
addRandomNum(Used);
}
// Look at the new randomized array
console.log(Used);
You could shuffle the array, if that is what you want.
There are shuffle functions if you follow this link of css-tricks:
https://css-tricks.com/snippets/javascript/shuffle-array/
I like technique 2. Which uses the sort function to randomly create a negative or positive number which will sort the items according to the returned value.
If the returned value is positive, the first item will precede the second that is passed to the function. As you can see, the parameters are unused because we don't want a logic sort but a randomized based on a random number.
You could call it like this:
answerArray.sort(function(item1, item2) { return 0.5 - Math.random() });
Ok, I will assume a few things. Your answerArray looks like this:
var answerArray = [
{
"q_id": "1",
"prompt": "Is StackOverflow awesome?",
"a1": "Yes",
"a2": "No",
"correct": "a1"
}
];
First add a property like this
"random": Math.floor(Math.random() * 101)
This will create a random number that you can use to sort the array, like so:
answerArray.sort(function(a, b) {
return parseFloat(a.random) - parseFloat(b.random);
});
This way you can sort the questions randomly.

Categories

Resources