I'm making a javascript neural network and trying to put some entries into an object using for loops but I'm not getting the result I want.
I want to be able to get an object looking like:
{0 : {neuron1Sum : null}}
And I want to loop it to create multiple neurons and layers. It might be easier to understand once you see the code.
hiddenLayers : function() {
for(var i = 0; i < arguments.length; i++) {
numberOfNeurons = arguments[i];
hiddenLayer = {};
for (var j = 0; j < numberOfNeurons - 1; j++) {
hiddenLayer[i] = ["neuron" + j + "Sum"];
hiddenLayer[i]["neuron" + j + "Sum"] = null;
}
}
},
Your hiddenLayer should be defined as array and hiddenLayer[i] should be defined as object. Then put each element to object like this way.
hiddenLayers : function() {
var hiddenLayer = []; // defined as array
for(var i = 0; i < arguments.length; i++) {
numberOfNeurons = arguments[i];
hiddenLayer[i] = {}; //defined as object
for (var j = 0; j < numberOfNeurons - 1; j++) {
hiddenLayer[i]["neuron" + j + "Sum"] = null;
}
}
return hiddenLayer;
/*
will return something like :
[
0 : {neuron1Sum : null, neuron2Sum : null},
1 : {neuron1Sum : null, neuron2Sum : null}
]
*/
},
Looks like you need to move a couple identifiers around and initialise an Array before the inner loop
// ...
hiddenLayers: function() {
var numberOfNeurons,
hiddenLayer = [], // keep this across all the loops
temp, // to store objects as we make them
i, j;
for (i = 0; i < arguments.length; ++i) {
numberOfNeurons = arguments[i];
hiddenLayer[i] = []; // remember to initialise
for (j = 0; j < numberOfNeurons - 1; ++j) {
temp = {};
temp["neuron" + j + "Sum"] = null;
hiddenLayer[i].push(temp);
}
}
return hiddenLayer; // remember to return
},
// ...
This code now produces something like
[
[
{neuron0Sum: null},
{neuron1Sum: null}
],
[
{neuron0Sum: null},
{neuron1Sum: null}
]
]
Starting in ES6 we will be able to use expressions in the property names of Object literals, e.g.
{
["foo" + "bar"]: "baz"
}
// produces
{
"foobar": "baz"
}
If you want your code to work in production right now, don't use this feature yet (maybe in a year or two)
I don't think that code is doing what you want, but I'm not sure what you want..
This assignment:
hiddenLayer[i] = ["neuron" + j + "Sum"];
sets hiddenLayer[i] to an array containing a single string. It's equivalent to this:
hiddenLayer[i] = [];
hiddenLayer[i][0] = "neuron" + j + "Sum";
Then this assignment:
hiddenLayer[i]["neuron" + j + "Sum"] = null;
Treats hiddenLayer[i] as a generic Object (associative array, map, hash, dictionary) and sets a named property (with the same name as that string) to null. So if i is 0 and j is 0, you get an object that looks like this:
{
0: "neuron0Sum",
neuron0Sum: null
}
I suspect that's not what you're trying to accomplish...
Related
I need to push object to array in Javascript, but every time push overwrite the same object I have had already added. For example:
//This is object list
var NewIssue = {};
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
In the end I will have newIssueList with 3 same objects. Why it does overwrite the first and how to solve this problem?
You have to move the object inside the loop.
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
var NewIssue = {};
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
myFunction();
console.log(newIssueList);
And then you could just extend the object literal a but to make it much more readable:
for (var i = 0; i < 3; i++) {
var NewIssue = {
Id:i,
Number:233+i,
Name:"Test"+i
};
newIssueList.push(NewIssue);
}
You can also avoid using a superfluous var by creating an inline object:
newIssueList.push({
Id: i,
Number: 233 + i,
Name: "Test" + i.toString()
});
There is only one object, and each time you push it into the array, you push a reference to the existing object. When you change the object, every element in the array reflects this, as they all point to the same object.
You need to create a new object on every iteration.
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
newIssueList.push({
id: i,
number: 233 + i,
name: "Test" + i.toString()
});
}
}
myFunction();
console.log(newIssueList);
I need to add the elements of arrays together in order, very similar to the question at [How can I add each element of one array to another one's corresponding element using a ParallelStream?, but I'm using javascript and angular. My arrays can come in with any amount of elements up to 31 (days), but they will all always be the same amount of elements across each data object.
$scope.test31days = {
"change_series": [
{ "data": [0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,0,0],
"name": "EMERGENCY",
"color": "#904040"},
{ "data": [0,1,3,0,0,0,0,1,2,3,3,0,0,0,2,1,1,1,0,0,1,1,3,3,1,0,0,1,2,2,0],
"name": "MINOR",
"color": "#333"},
{ "data": [0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0],
"name": "MAJOR",
"color": "#666"}
],
"change_title": "CHANGES"
}
My console output tells me I'm separating the elements correctly (to some extent), but when I run this with the if/else if statement, I crash the browser, so I know I'm screwing something up.
$scope.getTotalChanges = function(){
var series = $scope.test31days.change_series;
var arry = [];
for(var i = 0; i < series.length; i++){
// console.log('change_series loop #', i);
// console.log('change_series.data length', series[i].data.length);
var seriesData = series[i].data;
// console.log('series[i].name', series[i].name)
// console.log('seriesData', seriesData)
for(var j = 0; j < seriesData.length; j++){
console.log('For inner #', j);
console.log('seriesData #', seriesData[j]);
if (j = 0) {
arry = seriesData;
} else if (j > 0) {
arry[j] += seriesData[j]
};
}
}
// return series;
console.log('arry ', arry);
return arry;
};
My end goal is to have a single array of the data for the 31 (days)
var series = $scope.test31days.change_series;
var dataLength = series[0].data.length;
var result = Array.apply(null, new Array(dataLength)).map(Number.prototype.valueOf,0); //initialize result array with zeros
for(var i = 0; i < series.length; i++) {
for(var j = 0; j < dataLength; j++) {
result[j] += series[i].data[j];
}
}
I have a scenario in which i've to store array object in a array.My Javascript code is
var myArray= new Array(5,5);
for(dataIndex in data.data){
for(myIndex in data.data[dataIndex].myObject){
var xrow =data.data[dataIndex].myObject[myIndex].row;
var xcolumn =data.data[dataIndex].myObject[myIndex].column;
myarray[xrow][xcolumn] = data.data[dataIndex].myObject[myIndex];
}
}
but could not store any data object in the array.Can anyone help me out sort this?
It looks like you're coming from PHP, where an array is both a sequence of elements and/or key-value pairs? An array in javascript is just a sequence. (Actually, that's not 100% true, but it is for all intents and purposes.) What you want is an object. An object is a series of key value pairs. The keys and values can be any object, from a string to an array to a function.
var myObj = {};
// or assigning properties up front
var myOtherObj = {'foo': 'bar', 'baz': 12 };
My problem was not declaring and setting value for the javascript array.I was able to acheive it by this.
var YourArrayHere = new Array();
YourArrayHere.length = [first dimension array length here];
for(var count = 0; count < YourArrayHere.length; count++)
{
var TempSecondArray = new Array();
TempSecondArray.length = [sec dimension array length here];
YourArrayHere[count] = TempSecondArray;
}
Ok got a working demo. Took me a while to figure it out. Was fun. It can be optmized.
EDIT: you don't really need a MAX.
jsfiddle: http://jsfiddle.net/Grimbode/7B8CK/1/
var data = {
"data":[
{"myObject":[
{"row":0, "column":0},
{"row":0, "column":1},
{"row":0, "column":2},
]
},
{
"myObject":[
{"row":1, "column":0},
{"row":1, "column":1},
{"row":1, "column":2}
]
}
]
};
var result = new Array();
for(var i = 0; i < data.data.length; i++)
{
var temp = new Array();
var row = (data.data[i].myObject.length > 0) ? data.data[i].myObject[0].row: null;
for(var j = 0; j < data.data[i].myObject.length; j++)
{
console.log('row: ' + data.data[i].myObject[j].row + ', column: ' + data.data[i].myObject[j].column);
temp[data.data[i].myObject[j].column] = [data.data[i].myObject[j]];
}
if(row != null){ result[row] = temp;}
console.log(result);
}
console.log('Final:');
console.log(result);
jsfiddle: http://jsfiddle.net/Grimbode/7B8CK/
I represented data as best as I could to fit your example
var MAX_X = 10;
var MAX_Y = 10;
var data = {
"data":[
{"myObject":[
{"row":0, "column":0},
{"row":0, "column":1},
{"row":0, "column":2},
]
},
{
"myObject":[
{"row":1, "column":0},
{"row":1, "column":1},
{"row":1, "column":2}
]
}
]
};
var result = new Array(MAX_X);
for(var i = 0; i < data.data.length; i++)
{
var temp = new Array(MAX_Y);
var row = (data.data[i].myObject.length > 0) ? data.data[i].myObject[0].row: null;
for(var j = 0; j < data.data[i].myObject.length; j++)
{
console.log('row: ' + data.data[i].myObject[j].row + ', column: ' + data.data[i].myObject[j].column);
temp[data.data[i].myObject[j].column] = [data.data[i].myObject[j]];
}
if(row != null){ result[row] = temp;}
console.log(result);
}
console.log('Final:');
console.log(result);
I have surfed the problem but couldn't get any possible solution ..
Let's say i have a var like this
var data = [
{
'a':10,
'b':20,
'c':30
},
{
'a':1,
'b':2,
'c':3
},
{
'a':100,
'b':200,
'c':300
}];
Now , i need a multidimensional array like
var values = [[10,1,100], //a
[20,2,200], //b
[30,3,300]]; //c
What i have tried is
var values = [];
for(var key in data[0])
{
values.push([]); // this creates a multidimesional array for each key
for(var i=0;i<data.length;i++)
{
// how to push data[i][key] in the multi dimensional array
}
}
Note : data.length and number of keys keeps changing and i just want to be done using push() without any extra variables. Even i don't want to use extra for loops
If you guys found any duplicate here , just put the link as comment without downvote
Try this:
var result = new Array();
for(var i = 0; i < data.length; i++) {
var arr = new Array();
for(var key in data[i]) {
arr.push(data[i][key]);
}
result.push(arr);
}
also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable:
for(var i = 0; i < data.length; i++) {
result.push(new Array());
for(var key in data[i]) {
result[i].push(data[i][key]);
}
}
Ok, based on your comment I have modified the the loop. Please check the solution and mark question as answered if it is what you need. Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic.
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < Object.keys(data[0]).length; j++) {
result[j] = result[j] || new Array();
console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
result[j][i] = data[i][Object.keys(data[i])[j]];
}
}
I would like to have a for loop create objects as the children of a parent object. Usually, I would declare the object without using the for loop like this:
var mObj = {};
mObj.obj1 = {};
mObj.obj2 = {};
mObj.obj3 = {};
mObj.obj3.firstname = "john";
mObj.obj3.lastname = "superfly";
Now lets say I would like to employ a for loop to create the children objects of a parent object "mObj".
This is where I am going wrong:
var mArr = ["firstname","lastname","email"]; // This array holds the keys for the objects
var mObj = {};
var len = (mArr.length);
for(var i=0; i<len; i++){
var obj+i = {}
mObj = obj+i;
mObj.obj + i.mArr[i] = ""
}
So the outcome of this would be:
mObj.obj1.firstname = "";
mObj.obj2.lastname = "";
mObj.obj3.email = "";
I just cannot seem to name the object with counter that is being created within for loop like:
obj1
obj2
obj3
Any help would highly be appreciated.
Thanks.
var obj+i = {} is invalid syntax.
Try this:
mObj['obj' + i] = {};
If i == 1, this gives
mObj['obj1'] = {};
Which is equiavlent to:
mObj.obj1
But when constructing dynamically, you have to use the
mObj['obj' + i]
Formatting.
var mArr = ["firstname","lastname","email"],
mObj = {},
len = (mArr.length),
i = 0;
for(; i<len; i++){
myObj['obj' + i] = {}
myObj['obj' + i].mArr[i] = ""
}
You need to use the bracket syntax to assign a dynamic variable. For example:
var sampleObj = {};
for(var j = 0; j < 3; j++)
{
sampleObj["obj" + j] = { test: j };
}
This should produce the following object:
{
"obj1" : { test: 1 },
"obj2" : { test: 2 },
"obj3" : { test: 3 }
}
After running the loop then, you could validly use this statement:
var testVal = sampleObj.obj1.test;