I'm trying to create a basic for loop which creates an array but am a little confused in how to structure it... this is an example of the array:
var list = [
{id: "135", data: [9,129,345, 687]},
{id: "239", data: [596,382,0,687,33467]}
];
Those are just example numbers but i need to make it in a for loop (because the numbers come from variables, but i've got no idea how i do it =/
I know how to make a 1 dimensional array with a for loop but not anything this complex..
Does any one have an example loop to show how its structured?
EDIT: Just understood what you meant.
This is a bit of pseudo to show how you would create an array like the one in question
var list = [];
for(var i = 0; i < objectcount; i++){
// Here you need some way to get the ID for each should be dependant on 'i'
var obj = {id: 10, data: []}; object
for(var j = 0; j < datacount; j++){
// You need some way to retrieve each data number, dependent on 'j'
obj.data.push(somenumber)
}
list.push(obj)
}
OLD ANSWER
Assuming that you want to create an array of all the data arrays inside each object try something like this:
var newarray = [];
// This will iterate through each object in the list array.
for(var i = 0; i < list.length; i++){
// This will iterate though each value in the data array
// of the current list object
for(var j = 0; j < list[i].data.length; j++){
// Then you add that value to 'newarray'
newarray.push(list[i].data[j]);
}
}
Not sure if this is what you're asking, but to access the list object as shown you could
alert(list[0].id);
alert(list[0].data[0]);
and you would get 135 and 9 respectively.
Here's the for loops to see them all:
for (i=0; i<list.length; i++) {
alert (list[i].id);
for (j=0; j<list[i].data.length; j++) {
alert (list[i].data[j]);
}
}
Related
What I am trying to do is:
set an array value (list) to another array (options).
If the user's input (searchVal) matches with a list value it will delete options, push this match, and then will keep pushing the next matches without deleting options again.
So according to the code below, if searchVal was "whatever", options should return: ["whatever", "whatevEver1"] but, instead, it returns: ["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]
Relevant code:
var list = ["whatever", "WhatEver1", "whatttever"];
var clear = 0;
var options = [];
for (var i=0 ; i < list.length ; i++)
{
options.push([list[i]]);
}
var searchVal = window.prompt(" ");
for (var i=0 ; i < list.length ; i++)
{
if (list[i].toLowerCase().includes(searchVal.toLowerCase())) {
if (clear == 0) {
options.length = 0;
}
options.push([list[i]]);
}
clear++;
}
return options;
Js arrays are pass-by-reference. In order to make independent copy of array you need to use:
let options = JSON.parse(JSON.stringify(list));
I didnt try to implement this to your problem cause im too lazy but i think it might work.
I have an array of data containing another array of data with key(TypeOfServiceAssigned:Array(2)) common in both inner array, I want to apply ng-repeat in such a way that similar key-value will group together and differnt one group seperatly.
for better explaination see below:
Array = [
{
Quotation:1200,
TypeOfServiceAssigned:["Primary", "Partial Services"],
VendorEmail:"A#gmail.com"
},{
Quotation:1350,
TypeOfServiceAssigned:["Partial Services"],
VendorEmail:"Add#gmail.com"
}
];
I want to apply ng repeat over Array so that it will show me two group depending upon TypeOfServiceAssigned value , one for Primary and second for Partial Sevicers. And for Partial Sevicers, it will show me two list.
Most efficient method is to handcraft function to return exact what you want..
example here , then bind it to your nested ng-repeat as you would do normally :)
However normally we should do this on server side/service but anyway...
function doGroupBy() {
var result = {};
for (var i = 0; i < input.length; ++i) {
var current = input[i].TypeOfServiceAssigned;
for (var j = 0; j < current.length; ++j)
if (result[current[j]])
result[current[j]].push(input[i]); // result[current[j]] = [...result[current[j]], input[i]];
else
result[current[j]] = [input[i]];
}
return result;
}
var input = [{ Quotation: 1200, TypeOfServiceAssigned: ["Primary", "Partial Services"], VendorEmail: "A#gmail.com" },
{ Quotation: 1350, TypeOfServiceAssigned: ["Partial Services"], VendorEmail: "Add#gmail.com" }];
var testResult = doGroupBy(input);
for (var key in testResult) {
console.log('-----------');
console.log(key);
console.log(testResult[key]);
}
I'm pretty new to programming in general but have the problem that my array keeps being overwritten in my for loop so when I print in to the console only the last set of data is showing. i.e the data in the array is overwritten each time.
I want to store all the details in an array so I can work with the data. I have tried to put an array into an array but keep getting errors.
for (var i = 0; i < collection.length; i++){
var dailyfxTech = [];
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
How can I append the data to the dailyfxTech array each time it loops so that it looks like ;
dailyFxTech {[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], ...etc},
I later want to be able to reference the array to place the data in other parts of my site eg:
dailyFxTech[2,3] = the support of third ccy pair.
Thank you for your help.
Your issue is that each time the loop is running you are declariing a new array. Super simple fix. Just need to put the var dailyfxTech outside of your loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
Declare var dailyFxTech outside of the for loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
When you have the var declaration in the body of the for loop, the variable is re-allocated and the old value is trashed.
The following is my JSON data in a div:
[{"Identifier":"1","Label":"10 Day","Categories":"Standard","UpdatedBy":"Lno","UpdatedAt":"01-02-2013","RefId":"0","ComType":"1","Cs":["944"],"AM":"Error Message","Message":"asdfasdf","Combiner":[{"uniqueID":"1","type":"7","rule":""}]}]
I am accessing it through a JS object:
var myArrayVar=JSON.parse(document.getElementById("populateDT").innerHTML);
I want to iterate over this JS object. The following is my code, but it doesn't access my key/value fields:
for(var i=0; i<=myArrayVar.length;i++){
for(var j=0; j<=myArrayVar.Combiner.length; j++){
var sessionUniqueId= myArrayVar.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=myArrayVar.Combiner[j].type;
alert(sessionType);
var sessionRule=myArrayVar.Combiner[j].rule;
alert(sessionRule);
}
}
Can anyone suggest a solution?
for (var i = 0; i < myArrayVar.length; i++) {
for (var j = 0; j < myArrayVar[i].Combiner.length; j++) {
var sessionUniqueId = myArrayVar[i].Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType = myArrayVar[i].Combiner[j].type;
alert(sessionType);
var sessionRule = myArrayVar[i].Combiner[j].rule;
alert(sessionRule);
}
}
You never use i. You need it to access the current array element, for example:
for(var j=0; j<=myArrayVar[i].Combiner.length; j++){
myArrayVar is your array, myArrayVar[i] is the i-th element in that array and myArrayVar[i].Combiner is the combiner (array) property of the i-th element.
You'll make it yourself a lot easier if you give the current element a name as well. (You probably want to come up with a less generic name such as current though.)
for(var i=0; i<myArrayVar.length;i++){
var current=myArrayVar[i];
for(var j=0; j<current.Combiner.length; j++){
var sessionUniqueId=current.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=current.Combiner[j].type;
alert(sessionType);
var sessionRule=current.Combiner[j].rule;
alert(sessionRule);
}
}
Also, i cannot equal myArrayVar.length as that index is already out of bounds. Your loop condition should have < instead of <=.
You have an array with one element. That element is in myArrayVar[0] and it is an object. To iterate over the object use a for ... in loop.
var myObj = myArrayVar[0];
for(var key in myObj){
var value = myObj[key];
console.log(key, value);
}
You should also use console.log for debugging. It will show you more information about objects than alert can.
Try using "<" instead of "<=" in the for loops, and "myArrayVar[i].Combiner" instead of "myArrayVar.Combiner".
There are a couple of problems I see. First, your i and j variables go one spot too far. They should be using < instead of <=.
Secondly, you're declaring variables inside the loop. That's fine, but JavaScript isn't block scoped, so you really end up with the same three variables overwriting each other as many times as there are items in the list. Your example data only has one item so you probably won't notice the overwriting problem just yet–but once you have multiple items in the list it could be a problem.
Example, I have an array called 'categories' with the value ['4','9']. I'm trying to use that value with the name of a previously defined array. I have several arrays defined earlier called row1, row2, row3 etc. I'm also using jQuery.
Trying to do something like this:
for (i=0; i<categories.length; i++) {
row+categories[i].push($(this).attr('id'));
console.log(row+categories[i]);
}
Obviously row+categories[i] doesn't work, but maybe gives you an idea of what I'm trying to do? In this case to push that id value onto the array 'row4' the first time it loops through and then 'row9' the second time.
Thanks for your help!!
Rather than defining multiple row1, row2, row3 etc., why not define a single rows variable that contains multiple arrays?
var rows = [[], [], []];
var categories = ['4', '9'];
for (i = 0; i < categories.length; i++) {
rows[categories[i]].push($(this).attr('id'));
console.log(rows[categories[i]]);
}
It could even be an object with properties if that makes sense in your situation:
var rows = {
row1: [],
row2: [],
row3: [],
getRow: function(index) {
return this["row" + index];
}
};
var categories = ['4', '9'];
for (i = 0; i < categories.length; i++) {
rows.getRow(categories[i]).push($(this).attr('id'));
console.log(rows.getRow(categories[i]));
}
You can use eval(), even if i don't like it personnaly...
for (i=0; i<categories.length; i++) {
eval("row" + categories[i] + ".push($(this).attr('id'))");
console.log(eval("row" + categories[i]));
}
do you want a global or local variable? (the code below uses global variables)
var rowVar;
for (i=0; i<categories.length; i++) {
rowVar = "row"+categories[i];
window[rowVar].push($(this).attr('id'));
console.log(window[rowVar]);
}