finding information inside of nested arrays - javascript

I have an array that stores the values:
var array = [['favorite color'],['black','red']]
to get black I would:
document.write(array[0][1][0]);
then if i append to the array another question [['favorite thing']['box','ball']]
If I wanted ball I would:
document.write.array[1][1][1];
I am having trouble understanding arrays. I want an array with one question and multiple answers then I want to loop through them and display everything. I can do the loop but I am unsure how to find things in nested arrays once I create them.

Use a combination of objects (which work like dictionaries) and arrays. For example:
var array = [
{'question' : 'favorite color', 'choices' : ['black','red'] },
{'question' : 'favorite thing', 'choices' : ['box','ball'] }
]
for( var i = 0; i < array.length; i++ ) {
var question = array[i]['question'];
var choices = array[i]['choices'];
// here you can display / write out the questions and choices
}
Bearing in mind, creating a class and using a constructor or init methods would probably be better to encapsulate the idea of questions and answers. But the above is the basic idea.

var array = [['favorite color'],['black','red','blue']];
document.writeln(array[1][1]);
document.write(array[1][2]);
​
Would print red then blue see it working live : http://jsfiddle.net/HJ872/
How?
array[0] => gets an *array* = ['favorite color']
=> array[0][0] gets this first element `favorite color`
array[1] => also gets this array = ['black','red','blue']
=> and then [1][1] will get 'red', [1][2] will get `blue`

Related

Select Random Item (shown in pairs) from Array & Remove It, Restart Once Array is Empty

I'm super newbie in coding and I need help to achieve this code.
I'm trying to get a random item (in pairs) from an array and then remove it from this array until user gets to the last item or 60 days have gone from using the service (cookie?)... I have build a script with the help of other questions here in stackoverflow and here is my results so far.
`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];
var yourPics = [
dogpics,
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg' ] //This array has 52 cards but I cutted it for example purposes
];
function get_random_number(array){
return Math.floor(Math.random() * array.length |0);
} // here is where I have tried to modify with other scripts like the one in this page https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty with no success
randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});
var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
</script>`
Thank you for your help!
I don't fully understand what you mean by "remove in pairs", but I'll answer presuming you mean you wish to remove the image ending in 02F.jpg at the same time as removing the image ending in 02B.jpg, and then 03F.jpg at the same time as 03B.jpg.
The solution to this that I will propose is that we will structure your data a bit differently to begin with. That is, if those images, the "B image" and "F image" are linked, we could keep them in the same `javascript object. This would look like:
var yourPics = [
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
},
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
}...]
This would then be an array of objects, rather than strings. We can access the bImage property of an object with just
myObject = yourPics[0]
myObject.bImage
We could delete one of those objects those at random via splice.
myRandomlyRemovedObject = yourPics.splice(myIndexToDeleteFrom, 1) would remove 1 object from yourPics at position of myIndexToDeleteFrom, which you presumably would choose randomly. myRandomlyRemovedObject would be assigned to the one object we removed.
I think this object based approach is safer since you will know for a fact that you will removed both matching strings at the same time.

Accessing nested array in JavaScript

I wrote some code where data is going into an array. At each index, I have another array that has an array with five data elements. What I want to do is to add data at the end of each nested array.
var allTimeStamps = [];
var allTimeStampsData = [];
$.getJSON( "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo", function( data ) {
const responseData = data;
for(let key in responseData["Time Series (Daily)"]){
allTimeStamps.push(key);
allTimeStamps.push(parseFloat((responseData["Time Series (Daily)"][key]["3. low"])));
allTimeStamps.push(parseFloat(responseData["Time Series (Daily)"][key]["1. open"]));
allTimeStamps.push(parseFloat(responseData["Time Series (Daily)"][key]["4. close"]));
allTimeStamps.push(parseFloat(responseData["Time Series (Daily)"][key]["2. high"]));
allTimeStampsData.push(allTimeStamps);
allTimeStamps=[];
}
console.log("seperatedData", allTimeStampsData);
});
I am trying something like this:
Old
allTimeStampsData[0].append("121");
New
allTimeStampsData[0].push("121");
I wrote append because of Python. I was actually trying to push, but this is not working.
I am expecting output like:
[ ["08-2-2018",98,12,98,78,121] ,......]
The best way to do something like this is with a simple .map over the entries of the "Time Series (Daily)" property, from which you can extract the date and the low/open/close/high:
fetch("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo")
.then(res => res.json())
.then(responseData => {
const daily = responseData["Time Series (Daily)"];
const keys = [
'3. low',
'1. open',
'4. close',
'2. high',
];
const allTimeStampsData = Object.entries(daily)
.map(([date, infoObj]) => (
[date, ...keys.map(key => infoObj[key])]
));
console.log(allTimeStampsData[0]);
console.log(allTimeStampsData);
});
I believe what you're looking for is the push method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Initialize your array
var my_arr = ['Volvo', 'Ford', 'Chevrolet'];
Then use the push method to add a new value to it.
my_arr.push('Mercedes');
Now my_arr = ['Volvo', 'Ford', 'Chevrolet', 'Mercedes'];
You should explicitly assign the field in your allTimeStampsData array:
allTimeStampsData[allTimeStampsData.length] = allTimeStamps;
Thereafter, allTimeStampsData[i].push("121"); will work.
I think the original question needs to be clarified here folks. As #josh mentioned that you use $.push() to append data to the end of an array. Regardless of how many levels deep the Array is using .push() is the best way to add data to an array. Also this sounds like a duplicate question which is posted here javascript-push-multidimensional-array

Get keys from javascript array

Hello i have selectbox to show from javascript array.
<h6><strong>Brand</strong></h6>
<select data-placeholder="Brand..." multiple id="brand" style="width:200px;height:50px;margin: 0;">
<script language="javascript">print_brand1("brand");</script>
</select>
But when i choose one of selectbox data then it get values. Here is javascript code
var brand_arr = new Array(
1:"Acer",
2:"Dell"
);
function print_brand1(brand_id){
var option_str = document.getElementById(brand_id);
option_str.length=0;
option_str.selectedIndex = 0;
for (var i=0; i<brand_arr.length; i++) {
option_str.options[option_str.length] = new Option(brand_arr[i],brand_arr[i]);
}
}
How do i get keys (not values) when i choose one of selectbox data?
Your code will not work in its current state, however if you insist on keeping your current array structure you would need:
var brand_arr = {
1: "Acer",
2: "Dell"
};
Which syntactically makes little sense, assigning a key of 1/2 makes little sense when you could just get this number by using the current index + 1.
Note that with the changes above, in order to assign the keys 1 and 2 we are having to iterate over a Javascript Object and not a Javascript Array.
If you wanted to print 1 and 2 you could then do:
for(var k in brand_arr) {
if(brand_arr.hasOwnProperty(k)) {
console.log(k); // key
console.log(brand_arr[k]); // value
}
}
Although this answers your problem, I would still consider the structure of your data, it would make much more sense to have something like:
var brand_arr = [
{ brand: 'Acer', price: 200 },
{ brand: 'Dell', price: 200 }
];
Note how in the above example we can add extra details about that brand in the JSON. We could then iterate over the brand array to get more detail about each brand in a much more readable format opposed to a user assigned index and its name.

Meteor 1.0 - Mongo queries using variables as key, including $inc

I'm working with a large dataset that needs to be efficient with its Mongo queries. The application uses the Ford-Fulkerson algorithm to calculate recommendations and runs in polynomial time, so efficiency is extremely important. The syntax is ES6, but everything is basically the same.
This is an approximation of the data I'm working with. An array of items and one item being matched up against the other items:
let items = ["pen", "marker", "crayon", "pencil"];
let match = "sharpie";
Eventually, we will iterate over match and increase the weight of the pairing by 1. So, after going through the function, my ideal data looks like this:
{
sharpie: {
pen: 1,
marker: 1,
crayon: 1,
pencil: 1
}
}
To further elaborate, the value next to each key is the weight of that relationship, which is to say, the number of times those items have been paired together. What I would like to have happen is something like this:
// For each in the items array, check to see if the pairing already
// exists. If it does, increment. If it does not, create it.
_.each(items, function(item, i) {
Database.upsert({ match: { $exist: true }}, { match: { $inc: { item: 1 } } });
})
The problem, of course, is that Mongo does not allow bracket notation, nor does it allow for variable names as keys (match). The other problem, as I've learned, is that Mongo also has problems with deeply nested $inc operators ('The dollar ($) prefixed field \'$inc\' in \'3LhmpJMe9Es6r5HLs.$inc\' is not valid for storage.' }).
Is there anything I can do to make this in as few queries as possible? I'm open to suggestions.
EDIT
I attempted to create objects to pass into the Mongo query:
_.each(items, function(item, i) {
let selector = {};
selector[match] = {};
selector[match][item] = {};
let modifier = {};
modifier[match] = {};
modifier[match]["$inc"] = {};
modifier[match]["$inc"][item] = 1
Database.upsert(selector, modifier);
Unfortunately, it still doesn't work. The $inc breaks the query and it won't let me go more than 1 level deep to change anything.
Solution
This is the function I ended up implementing. It works like a charm! Thanks Matt.
_.each(items, function(item, i) {
let incMod = {$inc:{}};
let matchMod = {$inc:{}};
matchMod.$inc[match] = 1;
incMod.$inc[item] = 1;
Database.upsert({node: item}, matchMod);
Database.upsert({node: match}, incMod);
});
I think the trouble comes from your ER model. a sharpie isn't a standalone entity, a sharpie is an item. The relationship between 1 item and other items is such that 1 item has many items (1:M recursive) and each item-pairing has a weight.
Fully normalized, you'd have an items table & a weights table. The items table would have the items. The weights table would have something like item1, item2, weight (in doing so, you can have asymmetrical weighting, e.g. sharpie:pencil = 1, pencil:sharpie = .5, which is useful when calculating pushback in the FFA, but I don't think that applies in your case.
Great, now let's mongotize it.
When we say 1 item has many items, that "many" is probably not going to exceed a few thousand (think 16MB document cap). That means it's actually 1-to-few, which means we can nest the data, either using subdocs or fields.
So, let's check out that schema!
doc =
{
_id: "sharpie",
crayon: 1,
pencil: 1
}
What do we see? sharpie isn't a key, it's a value. This makes everything easy. We leave the items as fields. The reason we don't use an array of objects is because this is faster & cleaner (no need to iterate over the array to find the matching _id).
var match = "sharpie";
var items = ["pen", "marker", "crayon", "pencil"];
var incMod = {$inc:{}};
var matchMod = {$inc:{}};
matchMod.$inc[match] = 1;
for (var i = 0; i < items.length; i++) {
Collection.upsert({_id: items[i]}, matchMod);
incMod.$inc[items[i]] = 1;
}
Collection.upsert({_id: match}, incMod);
That's the easy part. The hard part is figuring out why you want to use an FFA for a suggestion engine :-P.

JavaScript: Access object variable inside nested array

How would I access ArrayObjectVariable inside
ArrayObject[0]? I know if you don't have a [ ] around it its as simple
as ArrayObject[0].ArrayObjectVariable?
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{ ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0]???);
I didn't realize the whole "ArrayObject[0][0].ArrayObjectVariable" thing. Thanks for the replies. I was trying it with just one ("[0]") instead of two ("[0][0]"). My second question is, what is the second "[0]" for? I just tried making multiple variables and it still used "[0][0]" ? So what's the second "[0]" controlling?
Third question? I noticed that it created a variable outside the array when I did that? When I change the value of the variable in the array, it has no effect on the one outside of it? Likewise, when I change the value of the variable outside of the array it has no effect on the one inside it. Is there a way to create the array without creating a variable outside of the array with the same name? Thanks :)
OK figured it out :) Just make the Object in the array without the "[ ]". The whole point of this was to figure out how to access nested items but I got it now. Didn't realize how to make them without the "[ ]". Example for those of you struggling like I was:
// create variables that we are going to use in Array Objects. Or make a function with the values.
var ATV1 = 'AyTeeVeeOne', ATV2 = 'AyTeeVeeTwo', ANV1 = 'AyEnVeeOne';
var ATV3 = 'AyTeeVeeThree', ATV4 = 'AyTeeVeeFour', ANV2 = 'AyEnVeeTwo';
// Make an Array
var ArrayObject;
ArrayObject = [{}];
// Insert variables into Array object(s).
ArrayObject[0] = {ArrayTestObject1 : { ArrayTestValue1:ATV1,
ArrayNestedObject1:{ ArrayNestedValue1:ANV1 },
ArrayTestValue2:ATV2
}};
ArrayObject[1] = {ArrayTestObject2 : { ArrayTestValue3:ATV3,
ArrayNestedObject2:{ ArrayNestedValue2:ANV2 },
ArrayTestValue4:ATV4
}};
// Access Array Object Variables
alert(ArrayObject[0].ArrayTestObject1.ArrayTestValue1) // Example 1
alert(ArrayObject[1].ArrayTestObject2.ArrayNestedObject2.ArrayNestedValue2) // Example 2
ArrayObject[0][0].ArrayObjectVariable
You have an array for the value of ArrayObject[0], so treat it like any other array.
use this:here you have ArrayObject as array and you are creating index as zero to the array and in that on zeroth place ArrayObjectVariable key resides.
<script>
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{
ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0][0].ArrayObjectVariable);
</script>

Categories