I need help regarding insertion of array elements as objects into another array in Javascript. I have the following code:
tableLength = 3;
nyCourt = [];
oldArr = [Buy, String, Question]
for (var t = 0; t < tableLength; t++) {
nyCourt.push({});
for (var i = 0; i < OldArr.length; i++) {
nyCourt.Title = OldArr[i] ;
}
};
The code isnt working, I want output in the following format
[{Title:Buy },
{Title: String},
{Title: Question}]
But the output I get is this:
[{Title:Question },
{Title: Question},
{Title: Question}]
This line:
nyCourt.Title = OldArr[i]
writes to the Title property on the nyCourt object (which is an array object), repeatedly in the loop. The last assignment wins.
But given what you've said you want your output to be, your code is over-complex. You only need one loop:
var nyCourt = [];
var oldArr = [Buy, String, Question];
for (var i = 0; i < oldArr.length; i++) {
nyCourt.push({Title: oldArr[i] });
}
Live Example (use Chrome or something else modern) | Source
Or as this is Node so we know we have map:
var oldArr = [Buy, String, Question];
var nyCourt = oldArr.map(function(entry) {
return {Title: entry};
});
Live Example | Source
//this give the output you want
tableLength = 3;
nyCourt = [];
oldArr = ['Buy', 'String', 'Question'];
for (var t = 0; t < oldArr.length; t++) {
nyCourt.push({Title: oldArr[t]});
};
console.log(nyCourt);
place that push function inside the loop also change the code like this
for (var t = 0; t < tableLength; t++) {
for (var i = 0; i < OldArr.length; i++) {
nyCourt.push({"Title": oldArr[t]});
}
};
Related
I need to check from a string, if a given fruit has the correct amount at a given date. I am turning the string into a 2d array and iterating over the columns.This code works, but I want to know : is there a better way to do it? I feel like this could be done avoiding 4 for loops.
function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < colCount; j++) {
var temp = rows[i].split(',');
if (!arr[i]) arr[i] = []
arr[i][j] = temp[j];
}
}
for (var i = 1; i < colCount; i++) {
for (var j = 1; j < rows.length; j++) {
verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
}
}
This would be a good candidate for Array.prototype.map
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})
What map does is iterate over an array and applies a projection function on each element returning a new array as the result.
You can visualize what is happening like this:
function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];
I want to write a function that takes an array such as:
var columns = ['distance', 'times', 'acceleration']
Then from this array, I want to generate something like this:
[{id: id_0, distance: 0, times: 0, acceleration: 0}, {id: id_1, distance: 1, times: 1, acceleration: 1}]
Notice that we have 2 objects here, but I want it to be whatever number I pass in to my parameter. Here is what I have:
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0, rowLen = rows.length; i < rowLen; i++) {
for (var n = 0; i < columns.length; n++) {
// not sure how to construct an object here from looping through my columns array
generatedData.push({
id: 'id_ + n',
// confused here
});
}
return generatedData;
}
}
This is the perfect place to dynamically create your own function. Try this:
function createArrayOfObjects(columns, count) {
var objectProps = new Array(columns.length);
for (var i = 0; i < columns.length; i++){
//":j" will be the variable j inside the dynamic function
objectProps[i] = columns[i] + ":j";
}
var funcBody = "var arr = new Array(count);" +
"for(var j = 0; j < count; j++){" +
"arr[j] = {" + objectProps.join(',') + "};" +
"}" +
"return arr;";
//Create a new function and call it with count as the parameter, returning the results
return new Function("count", funcBody)(count);
}
var count = 10;
var columns = ['distance', 'times', 'acceleration'];
createArrayOfObjects(columns.concat('id'), count);
This has the benefit of only having to loop over the columns array once where other solutions require nested loops.
JSPerf
I am giving you away the initial non-optimized solution. Its upto you to do the optimizations.
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0; i < rows.length; i++) {
var myObj = {};
myObj["id_" + i] = i;
for (var n = 0; n < columns.length; n++) {
myObj[columns[n]] = i;
}
generatedData.push(myObj);
}
return generatedData;
}
A functional approach that will take the object properties from the passed in array, instead of hard-coding them, might look something like this inside the for loop to populate an array named 'rows' with property names coming from the values of an array named 'cols':
cols.forEach(function(cv, ci, ca) { rows[ri][cv] = ri; });
See the snippet for a full example. Note that, in this example, I'm just shoving the current index of "rows" into the object as the property value.
var columns = ['distance', 'times', 'acceleration'];
function generateData(numRows, cols) {
rows = new Array(numRows);
for(ri=0; ri < rows.length; ri++) {
rows[ri] = { id: ri };
cols.forEach(function(cv, ci, ca) {
rows[ri][cv] = ri;
});
}
return rows;
}
data = generateData(5, columns);
console.log(data);
I have a piece of code to create an object literal array. The array is created from 2 other string array, one will become the object literal colHeads and the other array will be the data dataArr.
colHeads = [name, state]
dataArr = [John A. Smith,Joan B. Jones]
var temp = [];
var tempObj = {};
for (var i=0; i<colHeads.length; ++i) { // columns
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[i]] = dataArr[j];
}
temp.push(tempObj);
}
The final array should look like this:
var data = [
{name: 'John A. Smith', state: 'CA'},
{name: 'Joan B. Jones', state: 'NY'}
];
Problem here is according to this line tempObj[colHeads[i]] = dataArr[0]; The object literal would be replaced with the last entry in both arrays which make the result look like this:
var data = [
{name: 'Joan B. Jones', state: 'NY'},
{name: 'Joan B. Jones', state: 'NY'}
];
I'm new to javascript so I don't know much the syntax
First off, your loop is accessing the same dataArr index, it should be using j
tempObj[colHeads[i]] = dataArr[j];
Second, you are not constructing new tempObjs for each loop, so each item index shares the same tempObj which will end up leaving you with a list of the same exact object.
So far your code should look something more like this:
var temp = [];
for (var i=0; i<colHeads.length; ++i) { // columns
var tempObj = {};
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[j]] = dataArr[j];
}
temp.push(tempObj);
}
Lastly, You are only creating one tempObj for each column, rather than each row as you should be doing.
var temp = [];
var rowCount = colDatas[0].split(',').length;
for (var i = 0; i < rowCount; ++i) { // rows first
var tempObj = {};
for (var j = 0; j < colHeads.length; ++j) { // now columns
tempObj[colheads[j]] = colDatas[j].split(',')[i];
}
temp.push(tempObj);
}
Now, due to the way your colDatas object is set up, it requires you to split them for every loop which can become pretty costly, I suggest you find another way to store that so it can be better optimized.
Create new object in cycle (prepare arrays before it), like this:
for (var i=0; i<colHeads.length; ++i) {
var tmpObj = {};
tmpObj.name = colHeads[i];
tmpObj.state = colDatas[i]
result.push(tmpObj);
}
I'm new to javascript. So this question might not be good.
var arrQue = new Array(10);
for (var i = 0; i < 10; i++) {
arrQue[i] = new Array(6);
}
This code works perfectly but I wanted to know without giving the array size, how can I make something like this (the following code doesn't work):
var arrQue = new Array();//don't know the size
for (var i = 0; i < arrQue.length; i++) {
arrQue[i] = new Array();//don't know the size
}
And also the code contains two times creating new array. Is there easier or best way to do that creating multiple array?
And later I've to access like this:
arrQue[0][6] = "test";
arrQue[23][3] = "some test";
I found this method but think wrong somehow?
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var arrQue = [];
var size = Object.size(arrQue);
for (var i = 0; i < size; i++) {
arrQue[i] = [];
var nextSize = Object.size(arrQue[i]);
}
var arrQue = [];
for (var i = 0; i < length of your inputs; i++) {
arrQue.push(input);
}
Take a look here
Check out the Array Object Methods there.. that's all the stuff you need.
You can have arrays,arrays of objects... etc..depending upon your requirement.
var arrQue = [];
for (var i = 0; i < 10; i++) {
arrQue.push(input);
}
you might be looking for the push method:
var arr = [];
arr.push(your value);
How I can split a string into 2D array. String is like
1c2c3r4c5c6r6c8c9
array should be like
[[1,2,3],
[4,5,6],
[7,8,9]]
var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/);
for (var i = 0; i < rows.length; i++)
rows[i] = rows[i].split(/c/);
Please note that I didn't test this so it might contain a syntax error or something...
You can use the map method on Array
var s = "1c2c3r4c5c6r6c8c9";
var rows = s.split("r");
result = rows.map(function (x) {
return x.split('c');
}));
map is introduced in ECMAScript5 and is not supported in older browsers. But, there is a decent work-around here
var str = "1c2c3r4c5c6r6c8c9";
var result = [];
var group = str.split("r");
for(i in group) {result.push(group[i].split("c"))};
result should be what you want.
This should work:
var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/g);
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(/c/g);
for (var j = 0; j < cells.length; j++) {
cells[j] = parseInt(cells[j]);
}
rows[i] = cells;
}