Arrays inside an array Javascript [duplicate] - javascript

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 5 years ago.
I want to make an array so that it contains some identity name and for each of those names there is another array associated. My approach is like,
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var data = someServiceCall(i, x);
var identityName = i + '-' + x;
myArray[identityName] = data;
}
}
after executing this i get something like,
[1-1: Array(8), 1-2: Array(10), 1-3: Array(10), 1-4: Array(10),.. etc]
the next time I call this function I need to check whether 1-1 exists and if yes I need to get the list related to 1-1. How can I do this..? if 1-1 is not in the myArray I will call some other function.

To check if the element having the 1-1 key exists just do:
if("1-1" in myArray)
Then to access the array associated with 1-1 use:
myArray["1-1"]

Try this. It inserts an object containing the identity name and data in each array element.
var myArray = [];
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var data = someServiceCall(i, x);
var identityName = i + '-' + x;
var objectInArr = {
'identityName': identityName,
'data' : data
};
myArray.push(objectInArr);
};
};

try like this
myArray["1-1"] != undefined

Check if key exists in your array or not and act accordingly. Following is a working code snippet
var myArray = [];
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var identityName = i + '-' + x;
myArray[identityName] = [1, 2];
}
}
var key = "0-0";
if(myArray[key])
console.log(myArray[key]);

you can check your array lenght and if the array is empty you will know that you need to call another action as you say. something like below might work for you
if (myArray.length === 0) {
//Call another function}
else {
//Somthing else}

Related

Recursive function inside for loop not working as expected [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I was trying to print first array element using recursive function but output is not as expected.
var modelArray = [1,2,3];
var refurbArray = [a,b];
for (var z = 0; z < modelArray.length; z++) {
for (var y = 0; y < refurbArray.length; y++) {
var check = modelArray[z];
var recursive(refurbArray[y], function() {
consol.log(check);
});
}
}
Expected output:
1
1
2
2
3
3
Obtained output:
3
3
3
3
3
3
The problem you are having is that recursive have deferred the call to your call back function (likely due to some async functionality inside the recursive), and the value of check has changed when the callback function is finally executed.
You need to bind the check in a closure, for which there are several options and coding style on how to do, but example like
for (var z = 0; z < modelArray.length; z++) {
for (var y = 0; y < refurbArray.length; y++) {
(function() {
var check = modelArray[z];
recursive(refurbArray[y], function() {
consol.log(check);
});
})();
}
}
Try with something like:
var modelArray = [1,2,3];
var refurbArray = ['a','b'];
function recursive(val, cb){
cb();
}
for (var z = 0; z < modelArray.length; z++) {
for (var y = 0; y < refurbArray.length; y++) {
var check = modelArray[z];
recursive(refurbArray[y], function() {
console.log(check);
});
}
}
You print the check variable in the refurbCallback and that remains set to the last value of var check = modelArray[z];

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...
The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].
I declare the array
var parray = [[],[]];
I want to store the values in a loop something like this
for(counter = 0; counter < 10; counter ++){
parray[counter]['id'] += 1;
parray[counter]['isavailable'] += 0;
}
Later I want to loop through this and get the results:
for (var idx = 0; idx < parray.length; idx++) {
var pt = {};
pt.id = parray[schctr][idx].id;
pt.isavailable = parray[schctr][idx].isavailable;
}
Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??
Thanks for all the answers in advance.
JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.
You can start off with a blank array
var parray = [];
And "push" objects into it
for(counter = 0; counter < 10; counter++){
parray.push({
id : 1,
isAvailable : 0
});
}
Then you can read from them
for (var idx = 0; idx < parray.length; idx++) {
// Store the current item in a variable
var pt = parray[idx];
console.log(pt);
// read just the id
console.log(parray[idx].id);
}
Like I did here
What you want inside your array is just a plain object:
// just a regular array
var parray = [];
for(var counter = 0; counter < 10; counter++){
// create an object to store the values
var obj = {};
obj.id = counter;
obj.isavailable = 0;
// add the object to the array
parray.push(obj);
}
later:
for (var idx = 0; idx < parray.length; idx++) {
var pt = parray[idx];
// do something with pt
}

javascript / jquery get value of a variable [duplicate]

This question already has answers here:
Javascript "Variable Variables": how to assign variable based on another variable?
(3 answers)
Closed 9 years ago.
In javascript, the way to declare a var is: var msg = 'hello', and it is simply to call msg will get the value of 'hello'
if I am now have a number of var, e.g. msg_1, msg_2 ... msg_n would there be a way to get the value by calling something like
for (var i = 0; i < n; i++)
{
var var_name = 'msg_' + i;
alert (var_name)?
}
DEMO
for (var i = 0; i < 5; i++) {
var var_name = 'msg_' + i;
window[var_name] = i;
console.log(window[var_name]);
}
You should put the values inside an array.
var messages = ["first", "second", "third"];
for (var i = 0; i < n; i++)
{
alert (messages[i])
}
I would suggest use to use array instead of what you are doing.
var myVarialbes= [];
for (var i = 0; i < n; ++i) {
myVarialbes[i] = "some stuff" + i;
}
Here you got a simple method:
var var_name=''; //declare variable only once
for (var i = 0; i < 5; i++) //You should change 5 to n
{
var_name = 'msg_' + i;
alert (var_name.split('_')[1]);
}
function do_test(){
var v1 = "variable 1";
var v2 = "variable 2";
var v3 = "variable 3";
for (i=1;i<4;i++){
var o = eval("v"+i); // you actually need this
alert (o);
}
}
But why don't you use arrays?

loop different arrays javascript

Hello there am trying to save news tweets into three different array which are dynamically created.
am finding trouble when i want to get the text from each one of those array and make another request to twitter.
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
news_array[i] = [{user:user,date:date,profile_img:profile_img,text:text,url:url}];
}
for (var i = 0; i < news_array.length; i++) {
for (var x=0; x<i.length; x++){
console.log(news_array[i][x].user);
}
}
});
}
It doesn't show anything on the console.log.
thanks for the help!!!!!
First, make sure that your count is smaller than the data array's length, otherwise this could lead to some undefined values:
for (var i = 0; i < count && i < data.length; i++) …
Then, why are you creating all those one-element-arrays in the news_array? Just use only objects.
This would solve your actual issue: You are looping wrong over those inner arrays. The correct code would be
for (var i = 0; i < news_array.length; i++) {
for (var x = 0; x < news_array[i].length; x++){
console.log(news_array[i][x].user);
}
}
Also, you should indent your code properly. You have some odd braces around, which don't make the code readable.
The problem is the x<i.length in the for loop near the end. i is a number, so it doesn't have a length. You probably meant x < news_array[i].length.
You may try the following:
Use the push method to append elements / data in your array new_array
Use only 1 loop for to display the user value on console
So your code will be something like this:
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
// Pushing your elements in your array, 1 by 1
news_array.push({user:user,date:date,profile_img:profile_img,text:text,url:url});
}
// Here you only need 1 loop!
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i][x].user);
}
});
}
First thing is i would loop the first one till data.length rather than count because its an api and it "might" or "might not" return all the data. So it will be fool proof to loop till data.length
And your problem is with i.length
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i].user);
}
this should work. not sure why you had to loop through a loop.

Categories

Resources