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;
}
Related
I am new to js.
I am trying to write a code which reverses null terminated string.
I tried writing using push and pop.
but i am not getting output, can you tell me what is the problem.
providing code below
var word = "Cell0";
//var char = word.stringCharAT();
for (i=0; i< word.length; i++) {
var pushWord = [];
pushWord.push(word[i]);
for (j=0; j< pushWord.length; j++) {
var reverseWord= [];
reverseWord = pushWord[j].pop;
console.log("reverseWord" + reverseWord);
}
}
Here's a solution.
var word = "Cell0";
var reversed = '';
for (var i = word.length-1; i >= 0; i--) {
reversed += word[i];
}
console.log(reversed);
This loops through the characters of the string in reverse and adds the characters to a new string.
pushWord[j] is not an array, .pop is not called.
Define pushWord and reverseWord arrays outside of for loop, within loop, after word[i] is pushed to pushWord, call .unshift() on reverseWord with pushWord[pushWord.length -1] as parameter.
var word = "Cell0";
var pushWord = [];
var reverseWord = [];
for (let i = 0; i < word.length; i++) {
pushWord.push(word[i]);
reverseWord.unshift(pushWord[pushWord.length - 1]);
}
console.log("reverseWord" + reverseWord);
var originalWord = "Cell0";
var reverseWord = [];
for (let i = 0; i < originalWord.length; i++) {
reverseWord.unshift(originalWord [i]);
}
console.log(reverseWord.join(''));
You don't even need to push.
Another way to achieve the result!
I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source
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'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);
I have the following array (the code is written in Java) :
String[][] a = new String[3][2];
a[0][0] = "1";
a[0][1] = "2";
a[1][0] = "1";
a[1][1] = "2";
a[2][0] = "1";
a[2][1] = "2";
and what I want to do is to print 111222 and I accomplished that in Java by doing this:
for (int i=0;i < a[i].length;i++){
for(int j=0;j <a.length;j++){
System.out.print(a[j][i]);
}
}
What is the equivalent of this in JavaScript?
Here is the equivalent code in Javascript (no space its not a script version of java)
! edit missed the particulars of the loops, fixed now
var a = [];
a.push(["1", "2"]);
a.push(["1", "2"]);
a.push(["1", "2"]);
for(var i = 0; i < a[i].length; i++) {
for(var z = 0; z < a.length; z++) {
console.log(a[z][i]);
}
}
var arr =[
[1,2,3],
[4,5,6],
[7,8,9]
],arrText='';
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
arrText+=arr[i][j]+' ';
}
console.log(arrText);
arrText='';
}
Output:
for (i=0; i < a.length; i++) {
for (j = 0; j < a[i].length; j++) { document.write(a[i][j]); }
}
Though it would be smarter to add all the strings together and the print them out as one (could add to an element or alert it out.)
In javascript you can create multi dimensional array using single
dimensional arrays.
For every element in an array assign another array to make it multi
dimensional.
// first array equivalent to rows
let a = new Array(3);
// inner array equivalent to columns
for(i=0; i<a.length; i++) {
a[i] = new Array(2);
}
// now assign values
a[0][0] = "1";
a[0][1] = "2";
a[1][0] = "1";
a[1][1] = "2";
a[2][0] = "1";
a[2][1] = "2";
/* console.log appends new line at end. So concatenate before printing */
let out="";
for(let i=0; i<a.length; i++) {
for(let j=0; j<a[i].length; j++) {
out = out + a[i][j];
}
}
console.log(out);
var a = [];
a[0] = [];
a[0][0] = "1";
a[0][1] = "2";
a[1] = [];
a[1][0] = "1";
a[1][1] = "2";
a[2] = [];
a[2][0] = "1";
a[2][1] = "2";
for (i = 0; i < a[i].length; i++) {
for (j = 0; j < a.length; j++) {
document.write(a[j][i]);
}
}
js is very powerfull ; just use spread operator
mat = [[1,2,3],[3,4,5]]
mat.forEach(v=>console.log(...v));
// output
run the code see the output.
1 2 3
3 4 5