This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 8 years ago.
trying to create Create an array containing the names of at least three (3) fast food items and then, using a ‘for’ loop, display the array name, index number, and food item as shown below.
Fast Foods
fastFoods[0] is pizza
fastFoods[1] is burgers
fastFoods[2] is french fries
I can get the array but not the for to display like this.
Iterate over an array with for :
each array has a length property.Array indexing starts from 0 but length property starts count from 1.So in your for loop you have to set a condition which will iterate until the end of array is reached.for loop to iterate over an array has the following structure
for(i=0;i<array.length;i++){ // in your case it will be fastfood.length
//access elements here
}
++ is an increment operator.It will increase the value of i by one after each iteration.It is equivalent to i=i+1;
and inside for loop you can access the elements using the following structure
arrayName[index];
here arrayName is your array name( in this case fastfood) and index is the current i value;
so for your case it will be
fastfood[i]
To create an array with for :
first create a new array called fastfood
var fastfood=new Array() //or
var fastfood=[] // [] is a valid array notation
if you are goning to create an array using for loop you have to set a condition about how many elements you want to set in your array.For this case the structure will be
for(i=0;i<n;i++){} // here n is your desired number;
inside the for loop you can have a prompt method .It will allow you to enter a food element after each iteration.Prompt is not a good idea,but i assumed you are new to JS.Here is the structure:
fastfood[i]=prompt('enter food name');
var fastFood = ['pizza', 'burgers', 'french fries'];
for (var i = 0; i < fastFood.length; i++) {
console.log('fastFood[' + i + '] is ' + fastFood[i]);
}
Related
This question already has answers here:
Javascript sort array of objects using array of priority
(2 answers)
Closed 1 year ago.
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"},
{value:"11",type:"Plant"},{value:"10",type:"Fruit"},
{value:"16",type:"Plant"}]
What is the best/optimized way to sort this array such that I get all elements of type Fruit first and then the elements of type Animal (by picking elements from end of array).
expectedOutput = [{value:"10",type:"Fruit"},
{value:"15",type:"Fruit"},{value:"12",type:"Fruits"},
{value:"19",type:"Fruit"},{value:"13",type:"Fruit"},
{value:"71",type:"Animal"},{value:"61",type:"Animal"},
{value:"16",type:"Plant"},{value:"11",type:"Plant"}]
Note:- I don't need to sort it Alphabetically. It must be sort depending upon the specific type.
You can store the order of the type properties in an array, then subtract the index of the type property when sorting to determine precedence:
const order = ["Fruits", "Animal"]
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"}]
const sorted = array.sort((a,b) => order.indexOf(a.type) - order.indexOf(b.type))
console.log(sorted)
const arrPassword = []
const passarrayLength = 5
function addPassword(passwd) {
if(arrPassword.length === passarrayLength)
{
arrPassword.shift()
}
arrPassword.push(passwd)
console.log(arrPassword.length)
console.log(arrPassword)
}
addPassword('Pass')
addPassword('Pass2')
addPassword('Pass3')
addPassword('Pass4')
addPassword('Pass5')
addPassword('Pass6')
addPassword('Pass7')
addPassword('Pass8')
addPassword('Pass9')
addPassword('Pass10')
I have a few cases where I want to store objects like user password history in an Array of objects to ensure he has not used the password in the last 5 times for example. My question is can I specify an array of objects with a size of 5 and then just push new passwords to array and any object in the array above size set would be discarded ? Or do I have to do this my self where I count the objects in my Array and if it is = max size I pop the oldest one before I push the new object to array ?
Based on the research I did typescript or javascript does not have a fixed array size, I can specify a array of 3 5 objects but will need to assign all 5 and even so the push would make it 6 objects as there is no limit.
So what would be the best approach to handle this ?
I included some basic concept i cam up with
Can I specify an array of objects with a size of 5 and then just push new passwords to array and any object in the array above size set would be discarded?
Nope. Arrays in javascript do not have a maximum size, so there is no "built in" way to do this.
Or do I have to do this my self where I count the objects in my Array and if it is = max size I pop the oldest one before I push the new object to array?
Yep, that's exactly right. It shouldn't be too hard to make a little class that handles this logic.
When i need a functionality and there happens to be no such a functionality, the first thing that i think is "what am i missing?".
In this particular case all you need to do is to take the last passarrayLength many items from your arrPassword array and reassign it to the arrPassword array like;
arrPassword = arrPassword.slice(-passarrayLength);
like
[1,2,3].slice(-5); // <- [1,2,3]
[1,2,3,4,5,6,7,8,9].slice(-5); // <- [5,6,7,8,9]
Hello I am writing a game using javascript that takes the user's name as well as the "round" they made it to and stores it in two different arrays, and I would like to display the names coupled with the scores, highest to lowest but I'm stumped on how to do it, I can sort the rounds from highest to lowest but I can't figure out how to sort the names along with them. Please help!
my current code:
nameScore.push(username);
highScore.push(round);
highScore.reverse();
for (var i = 0; i < highScore.length; i++) {
$("#highScore").append(nameScore[i] + " " + highScore[i] + "<br>");
}
Don't use two arrays that are not linked in any way. Just use one array.
const userScores = [];
// Play game, get score
userScores.push({username, roundNumber, score});
Now you can search/sort this array and the username, the round number, and the score value are all linked together.
There are many suggestions in Stackoverflow on handling the synchronous sorting of several arrays. One idea that came to my mind is the creation of a sorted index array for stepping through the concerned arrays, that are left unsorted. Here is a short example with array nam, containing names and array num with the associated scores. The function mkidx(arr) expects the array to be sorted after as an argument (I chose num) and returns a sorted (in descending order) index array that can then be used to step through all unsorted arrays:
var nam=['eins','zwei','drei'];
var num=[10,200,30];
// create an index array:
const mkidx=arr=>arr.map((v,i)=>
({v,i})).sort((a,b)=> typeof a.v=="string"? a.v.localeCompare(b.v) : b.v-a.v).map(v=>v.i);
mkidx(num).forEach(k=>
console.log(k,nam[k]+': '+num[k])
)
I created the index-creation function such that it checks for the type of elements and then sorts either alphabetically (.localeCompare()) or numerically (descending).
Looking at a beginner's javascript book and trying to understand a small browser program that builds a list with user input. The input box displays and enters strings as input until he just adds " " as an input. Then the list is shown in the browser.
Here's the code:
var userInput = " ";
var namesArray = new Array();
while ( (userInput = prompt("Enter name", " ")) != " ") {
namesArray[namesArray.length] = userInput;
}
namesArray.sort();
var namesList = namesArray.join("<br />");
var listHolder = document.createElement('div');
var list = listHolder.innerHTML = namesList;
document.body.appendChild(listHolder);
I just don't have understanding of the way the author adds items to the array. Would someone care to explain how namesArray[namesArray.length] = userInput builds an array?
Also here's a fiddle to try it out
Thansk in advance!
So what happens is that, we get a while loop that is going to keep asking for a name until we get an empty response:
while ( (userInput = prompt("Enter name", " ")) != " ")
It then uses the length of the inital namesArray to index the new value.
namesArray[namesArray.length] = userInput;
So we know that the array is initially empty. So on the first run the length is going to be zero! We also know that an index of 0 is the first item in an array. So it adds it to the array as the first item. After that, the array now has a length of 1 (since we just added an item). So on the next iteration we add the new item to the array at the index of 1, which increases its length to 2. This goes on forver until we break the while loop.
So if we break it down we'll see it more clearly:
//First iteration
newArray.length = 0;
newArray[newArray.length] = newArray[0]
//Second iteration
newArray.length = 1;
newArray[newArray.length] = newArray[0]
etc.
Basically .length is the size of the array so .length is the next index of the array without anything in it yet. He just adds the string to the end of the array .length which creates a new position at the end of the array. .length - 1 is the last element of the array so .length would create a new position at the end of the array. The next time through the loop the length will be one greater than the previous time because you added an element to the array.
The condition for the while loop (userInput = prompt("Enter name", " ")) != " ") will remain true as long as a name is entered each time.
Each time a name is entered, the length index is assigned the name. Each time a name is assigned, the length increases. As a result, the array will grow for each name entered.
Normally you could easily add an element to an array via the .push() method. For example:
var ary = []; // empty array
ary.push('foo'); // the ary array now has one element, 'foo'
Now array indices are zero-based, meaning that you refer to the first element as [0], the second as [1], etc. However, the .length property will return the actual number of elements in an array. So if we add 10 elements to our array, asking for the length will give us 10.
So what the person who wrote that code is doing, is using the fact that the .length property will allow you to target an element of the array that doesn't exist yet -- the element after the last element.
So for example, say we have an array with 10 elements. The length property will be 10, however the index of the last item will be nine, since the indices are zero-based. When the author of that code does:
namesArray[namesArray.length] = userInput;
They're also saying namesArray[10] = userInput;, and assigning userInput to the eleventh spot in the array (remember, zero-index).
Since this can be a little confusing to follow, most programmers will simply use the .push() method, which automatically tacks the value you pass it onto the end of the array without you having to specify an index.
Since arrays are indexed starting from zero, the last element in the array always has the index
namesArray.length - 1
Therefore, the next available unused index is always equal to
namesArray.length
You can safely set values at this index and know that they will be added to the end of the array.
So, you have this array:
var namesArray = new Array();
And you may know you can insert array values like this:
namesAray[0] = 'first value';
namesAray[1] = 'second value';
namesAray[2] = 'third value';
Now, the code is like this:
namesArray[namesArray.length] = userInput;
So, here the namesArray.length brings you the size of the array. Ok, as above you see I've added three values to the namesArray namesArray[0],namesArray[1], namesArray[2]. So the current size of the array is 3 and namesArray[namesArray.length] is equal to namesArray[3] and now here the input value is inserted.
So, like this the code inserts new array value to the end index of array which is checked by while ( (userInput = prompt("Enter name", " ")) != " ") {
Hope you understood.
I am trying to push elements onto an array.
EDIT
task.prototype.goTest=function(){
for(a = 0; a < test.length; a++) {
if(this.testnumber != test[a].number) {
//it will only loop 8 times under conditional statement
group = {
title: test[a].Title,
ID: test[a].ID,
contents: []
};
this.company.push(group);
this.testnumber = test.number[a];
}
//outside of if conditional statement.. it will loop 15 times
//i want every test[a].conetents get pushed to group.contents array.
//this.company is the final variable I need for this function...
group.contents.push(test[a].contents);
}
console.log(this.company);
}
However, when I do
console.log(this.company);
I see 8 elmements with only 1 element in each group.contents array. The ideal situation is to have 8 elements with 2 to 3 elements in the group.contents array.
this refers to the object in the function.
Any idea how to solve my issue?
You are making a new group object each loop, so the reference to group.contents is only the current one, it does not reference the previously created group objects.
So, each time you call group.contents.push, you are only pushing onto the object created in that loop iteration.