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")];
Related
I want to predefine the 2d-array containing an array of objects like this below image:
I am trying this way:
var grid = [];
iMax = 3;
jMax = 2;
count = 0;
for (let i = 0; i < iMax; i++) {
grid[i] = [];
for (let j = 0; j < jMax; j++) {
grid[i][j] = count;
count++;
}
}
In your code you're building up the two-dimensional array, but you are filling the rows with numbers (i.e. your setting the count) instead of an array of objects. So if you want to achieve the exact same structure as provided in the screenshot, you can do:
const rows = 4;
const cols = 4;
const elementCount = 3;
function buildGrid(rows,cols, elementCount) {
const grid = [];
for(let i=0; i < rows; i++) {
grid[i] = [];
for(let j=0; j < cols; j++) {
grid[i].push(Array.from({length:elementCount}, () => ({})));
}
}
return grid;
}
const grid = buildGrid(rows,cols,elementCount);
console.log(grid);
I'm working with the problem below:
You are provided with an empty array called nestedArr. Using a for loop starting at index 0, add 5 subarrays to nestedArr, with each nested array containing the string 'loop' concatenated with the corresponding index in nestedArr as its first element, and the index as its second element.
Example of a subarray: ['loop3', 3].
This is what I've tried
const nestedArr = [];
for (var i = 0; i < 5; i++) {
nestedArr[i] = []
for(var j = 0; j < 2; j++) {
nestedArr[i][j] = 'loop'+[i], i
}
}
console.log(nestedArr)
It gives me [['loop0', 'loop0'], ['loop1', 'loop1'], ['loop2', 'loop2'], ['loop3', 'loop3'], ['loop4', 'loop4']]
Can't figure out how to have it in this format: ['loop3', 3].
Please guide me!
You can just construct the array literally or use a ternary operator to check the first index in the inner loop and concatenate the string loop
const nestedArr = [];
for (var i = 0; i < 5; i++) {
nestedArr[i] = ['loop' + i, i];
}
const nestedArr2 = [];
for (var i = 0; i < 5; i++) {
nestedArr2[i] = [];
for(let j = 0; j < 2; j++){
nestedArr2[i][j] = j == 0 ?'loop' + i : i;
}
}
console.log(nestedArr, nestedArr2)
const nestedArr = [];
for (let i = 0; i < 5; i++) {
nestedArr.push(['loop' + i, i]);
}
console.log(nestedArr);
I am creating an object with my XML data and pushing into the array. But when it coming out from the method I can see all the array value is copy of first one. Can anyone help me.
Here is my code :
var obj = {};
for(var i = 1; i < myData.length; i++) {
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++){
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}
You need to create a new object in the top level for loop. In your case you have only one variable, for which you are adding properties and push into the array it's reference. So at the end you have one big object and pushed the reference of it into the array for many times.
for(var i = 1; i < myData.length; i++) {
var obj = {};
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++) {
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}
I am writing a function which should create a 2 dimensional array pre-populated with zeros. My output looks correct, but apparently there is a bug in it that I am not seeing. Does anybody know what it is? I don't see it.
function createMatrix(size) {
var defValue = 0;
var row = [];
var matrix = [];
for (var i = 0; i < size; i++) {
row.push(defValue);
}
for (var i = 0; i < size; i++) {
matrix.push(row);
}
return matrix;
}
You're pushing the same row into your array matrix every time. These all point to the same array, since they are passed by reference.
You should make a new array for each row instead:
function createMatrix(size){
var defValue = 0;
var matrix = [];
for (var i = 0; i < size; i++) {
var row = [];
for (var j = 0; j < size; j++) {
row.push(defValue);
}
matrix.push(row);
}
return matrix;
}
The problem lies in the second loop;
If you stop and trace your code, you can see that you are only creating one "row" array whereas you most likely want to make size amount of rows.
Your code should probably look like this
var matrix = [];
for(var i = 0; i < size; i++) {
//temp row to append to array
var row = [];
//fill row array with 0s
for (var j = 0; j < size; j++) {
row.push(0);
}
//append row to the matrix
matrix.push(row);
}
return matrix
This way you are pushing a completed row at the end of each iteration.
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;
}