Get every variable loop value in array in JavaScript - javascript

How to get every variable of loop into an array and call all the variables in some other variable.
I am very new to array. I don't have any idea how to solve this.
Suppose I have an Array[]
and the variable in an array is i, so i1, i2, i3 ....... in
n is the number of times loop will run.
So
for (i=1; i<=n, i++) {
//I need an array called here.
//there will be some code play here
//There will be some value returned after the code it could be text or no.
}
then I want to assign all the values of array into a variable with comma separated
var k = array{} i.e k = "i1,i2,i3,......in"
I try to find on Google but not able to find any solution.
This example is a reference for what I want to achieve actually.

You will declare the array before you enter the for loop. You will then perform your logic and .push() the new values into the array inside of the for loop. After the for loop, you would then want to .join() the array. This will assign the values of your array as a string to your new variable.
var yourArray = [];
for(i = 1; i <= n; i++) {
// some logic...
yourArray.push(newValue);
}
var yourNewVariable = yourArray.join(", ");

While this should be very easy to Google, here's how you do it:
for (var i = 1; i <= k.length; i++) {
var item = k[i];
// ...do something with item
}
When you become more versed in JS, look into using .forEach or .map:
k.forEach(function(item) {
// ...do something with item
});

Related

Assign a array of indexes as an object value

I have an assignment which i need to sole but i am really stuck and can't make a progress. The assignment consist in an array of elements like this
const appleHolderLine = ['Rome', 'Ambrosia', 'Rome', 'RedDelicious', 'Akane','RedDelicious', 'SweeTango', 'RedDelicious', 'RedDelicious', 'Opal', 'Winesap', 'RedDelicious', 'Empire', 'RedDelicious', 'Liberty'];
Firstly it is needed to declare a variable lineCount which count for every element of the array and a reference to an object called appleMap.
Than the challenge consist in looping through the array and the elements of the array would be the object keys with no duplicates and the values would be an array of idexes of the specific element place of the array. To give an example how it should look like:
Example:
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
console.log (lineCount, appleMap)
Should Log:
5, {'GreenApples':[0], 'RedDelicious': [1,4], 'OrangeApples':[2], 'PurpleApples': [3]}
My progress so far
var lineCount = 0;
var appleMap = {};
for (let i = 0; i < appleHolderLine.length; i++){
lineCount++;
// if element in the array exist in the array
appleMap[appleHolderLine[i]] = [i];
}
Could you give me a hint of how to solve this, i am really stuck.
Basically you can create an empty array the first time and keep pushing like below
var lineCount = 0;
var appleMap = {};
for (let i = 0; i < appleHolderLine.length; i++){
lineCount++;
if(!appleMap[appleHolderLine[i]])
appleMap[appleHolderLine[i]] = []
appleMap[appleHolderLine[i]].push(i);
}
You could use Array.prototype.reduce which is a more advanced construct javascript provides. Please refer to answer by CodeManiac below for the same.
The above answer is to clarify the basic idea and hint on how you could think
Also, lineCount can be obtained by using appleHolderLine.length directly.
You don't need an extra variable ( Line count ) here, simply loop over the value use, use the index to access value, check if there's nothing present for that key then just initialize it with empty array, push index to the key in each iteration
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
var appleMap = {};
for (let i = 0; i < appleHolderLine.length; i++){
if(!appleMap[appleHolderLine[i]]){
appleMap[appleHolderLine[i]] = []
}
appleMap[appleHolderLine[i]].push(i);
}
console.log(appleMap)
You can simply use reduce
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
let final = appleHolderLine.reduce((op,inp,i)=>{
op[inp] = op[inp] || []
op[inp].push(i)
return op
},{})
console.log(final)
Line count is simply same as length of array, let lineCount = appleHolderLine.length
I suppose, the shortest answer is the functional one.
const appleHolderLine = ['GreenApples', 'RedDelicious','OrangeApples', 'PurpleApples', 'RedDelicious']
result = appleHolderLine.reduce((a,c,i) => { if(a[c]) a[c].push(i); else a[c]=[i]; return a; }, {})
console.log(result)
But I am not sure that you are expected to deliver a functional solution. Still, you might find it useful. The idea is that the reduce method starts with an empty object and iterates through the array. In each iteration, it checks if the current element c is already a field of the accumulator a. If so adds its index i to the specific field, if not, initializes the field with the current element as name and the index as a single-element array as value.

Array only being updated on first iteration of a for loop

The following code takes an array of objects structured like so: {html:whatever number:number value}.
function Org(data){
//array of objects
var Data=data;
for(var i=0; i<Data.length; i++){
var nums=[];
nums.push(Data[i].number);
console.log(nums);}
}
Nums should have be logged to the console as [1,1] on the second iteration when called with: [{html:null,number:1},{html:null,number:1}] but instead is logged as [1] on both the first and second iterations. Why might this be?
You need to move the initialization of num outside of the for loop. Inside it creates for each iteration a new empty array.
BTW, no need for using another variable for data.
function Org(data){
var nums = [];
for (var i = 0; i < data.length; i++){
nums.push(data[i].number);
}
console.log(nums);
}
Or shorter:
var Org=data=>console.log(data.map(e=>e.number));

Learning While Loops. Can't figure out what I am missing in my code.

Write a function called indexToString. This function should:
1. Take an array as an argument
2. Create and return a new array of all passed array elements as strings
3. Each strings should be formatted like so: “[index] is [element at index]”
This is the error I am getting: returns an array of passed-in array elements as strings with element index specified
expected undefined to deeply equal [ '0 is 1', '1 is 2', '2 is 3' ]
Here is my code:
var indexToString = function(array){
index = 0;
elementAtIndex = 0;
var i = 0;
while(i < array.length){
console.log(index + " is " + elementAtIndex);
i++
}
return array[i];
};
Two Three errors.
Firstly, the while loop will exit when i is no longer less than array.length; the first such number is array.length. This means, at the end of the loop, array[i] is array[array.length], which is just outside the array, thus undefined.
Secondly, you are supposed to return an array of strings, as told by your test failure message; not print them to the console.
EDIT: Thirdly, what Spencer said. :) Use i instead of index, and array[i] instead of elementAtIndex.
You want to start with an empty array outside the loop, and push each string you construct into it; then return that array after the loop.
Or you can do it with "new" JavaScript:
var indexToString = array => array.map((e, i) => `${i} is ${e}`)
You should reflect a bit more on your code, it is quite nonsense so far.
Let's decompose the question to identify what should be done:
Write a function called indexToString. This function should:
Take an array as an argument
Create and return a new array of all passed array elements as strings
Each strings should be formatted like so: “[index] is [element at index]”
So:
you create a function called indexToString which body contains the code, as you did.
In the initialization part before your while, you should create a new empty array that is going to be filled, and declare an integer called index for example initialized at 0 that is going to be used to loop through the original array. (Tip: var new_array = []; to create, and use new_array.push(elem); to append an element)
in your while, you should push at the end of your new array a string built as follow: "["+index+"] is ["+array[index]+"]" AND you should increment your index. You loop while(index < array.length).
At the end, you can return the new array !
Good luck with learning programming!
If the arraylenth is 10, the function will return array[10].This is an array-bound.
When you enter the last loop, the i becomes equal to array.length, so array[i] is undefined after this. But probably this is not what you wanted. you want to return the full array.
var indexToString = function(array){
var new_array = [];
var i = 0;
while(i < array.length){
new_array[i] = i + " is " + array[i];
i++;
}
return new_array;
};
console.log(indexToString([1,2,3]));

fastest way of getting an array of references from object keys

Suppose I have a global object that looks like this:
var TheFruits = {
323: {},
463: {},
223: {} ..... // can be thousands of properties
}
Basically, the keys are IDs and the values are themselves objects. Now suppose I have an array of IDs that I pass into a function and I want that function to return an array of references to the values that match the IDs of the global object (ie. no deep copy). Something like this:
function GetReferences(TheArrayOfIDs) {
var TheArrayOfReferences = [];
return TheArrayOfReferences;
}
Now I know I can write a for loop that iterates over TheArrayOfIDs and that then loops over the object keys at each iteration but then that's a loop within a loop. So I'm looking for the fastest way of doing it, and jquery is available.
Basically, if TheArrayOfIDs = [323, 463, 223]; then TheArrayOfReferences =[TheFruit.323, TheFruit.463, TheFruit.223];
Thanks.
You don't need a second loop:
var results = [];
for (var i = 0; i < ids.length; i++)
results.push(fruits[ids[i]]);
You have to do only one loop as key look-up is built-in :
var TheArrayOfReferences = TheArrayOfIDs.map(function(id){return TheFruits[id]});
Something like that should work :
var i = 0, l = TheArrayOfIDs.length;
for (i = 0; i < l; i++)
TheArrayOfReferences.push(TheFruits[TheArrayOfIDs[i]]);

sum index in JavaScript foreach

In the following code sample i get a strange behavior
var data = ['xxx', 'yyy'];
for (var i in data)
{
var a = i;
var b = data[i];
}
The two first iterations works just fine. I get index "0" and "1" in i, but then it loops one extra time and now the i is "sum". Is this by design or what is this extra iteration used for? The result in my case is always empty and it messes up my code. Is there a way to not do his extra loop?
BR
Andreas
It looks like you (or some other code you've included) have added extra properties onto the Array prototype. What you should be doing is checking to see whether the object you're iterating over actually has that property on itself, not on its prototype:
for (i in data) {
if (data.hasOwnProperty(i)) {
a = i;
b = data[i];
}
}
That said, you should never use for .. in on arrays. Use a regular for loop.
See here for more information: http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
You are looping through an Array, not through an Object. For arrays it's better to use:
for (var i=0; i<data.length; i=i+1){
/* ... */
}
In your loop every property of the Array object is taken into account. That makes the for ... in loop for array less predictable. In your case it looks like sum is a property (method) that's added to Array.prototype elsewhere in your code.
There are more ways to loop through arrays. See for example this SO-question, or this one
Just for fun, a more esoteric way to loop an array:
Array.prototype.loop = function(fn){
var t = this;
return (function loop(fn,i){
return i ? loop(fn,i-1).concat(fn(t[i-1])) : [];
}(fn,t.length));
}
//e.g.
//add 1 to every value
var a = [1,2,3,4,5].loop(function(val){return val+1;});
alert(a); //=> [2,3,4,5,6]
//show every value in console
var b = [1,2,3,4,5].loop(function(val){return console.log(val), val;});
Here's a way to safely iterate.
var data = ['xxx', 'yyy'];
for (var i = 0; i < data.length; i++)
{
var a = i;
var b = data[i];
}
What you are getting is an method coming from extending the Array object, I guess you are using some library where is something like
Array.prototype.sum = function () {...};
Perhaps setting data like this would work better: var data = {0:'xxx', 1:'yyy'};
First of all data is an object. Try to add console.log(a); and console.log(b); inside your loop and you'll see.

Categories