Transform multidimensional array by x value [duplicate] - javascript

This question already has answers here:
Transposing a 2D-array in JavaScript
(25 answers)
Closed 8 years ago.
If I have a large multidimensional array (matrix), how can rearange the elements so that I have "y" values as the new "x" values in the array?
Hard to explain so let me give you an example.
I want the below array.
[
[[0][1][2][3]],
[[4][5][6][7]],
[[8][9][10][11]],
[[12][13][14][15]],
]
to be transformed into the below array
[
[[0][4][8][12]],
[[1][5][9][13]],
[[2][6][10][14]],
[[3][7][11][15]],
]
for (var i = 0; i < tablesOfData.length; i++) {
for (var j = 0; j < tablesOfData[i].length; j++) {
//Transform the array
}
}

All rows needs to have the same number of columns.
If number of rows is the same as number of columns (like in your example), the following should work. If they are not the same then you need to create a n
for (var i = 0; < i tablesOfData.length; i++) {
for (var j = i; j < tablesOfData.length; j++) {
var temp = tablesOfData[i][j];
tablesOfData[i][j] = tablesOfData[j][i];
tablesOfData[j][i] = tablesOfData[i][j];
}
}
Otherwise you need to create a new table and add the values to that table, like this:
var newTable = new int[tablesOfData[i].length]();
for (var i = 0; < i tablesOfData.length; i++) {
for (var j = 0; j < tablesOfData.length; j++) {
if (i == 0)
newTable[j] = new int[tablesOfData.length]();
newTable[j][i] = tablesOfData[i][j];
}
}
I wrote the code in Notepad so it might not be the correct syntax to run on it's own but the logic should be right.

Related

How do i split up an array that holds an array?

Hello my fellow JS friends,
I am letting a user import a csv file (excel sheet) and i convert that into
an array. which has 472 rows and 87 columns in this case.
so my array looks like this:
and everything is separated by commas like a usual array.
The issue is I need to separate the array within the array and when i do that i get an array with the length of 9 million, which i think is wrong
vm.allTextLines = files.split(/\r\n|\n/);
var headers = vm.allTextLines[0].split(',');
vm.columnCount = headers.length;
vm.rowCount = vm.allTextLines.length - 1;
for (var i = 0; i < vm.allTextLines.length; i++) {
// split content based on comma
var data = vm.allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
vm.lines.push(tarr);
}
}
//this is where i split the array that contains the csv
//data and put it into its own array I believe this is
//where the issue is.
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
}
If you can help me correct this for each I would appreciate it alot.
Thank you in advance guys!
I agree with you about the place of error, because it seems you nested the loop in a wrong way. Following a snippet where you can check what I mean.
i.e:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
// Here you should not nest the loop
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
}
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
Of Course you could easily optimize the algorithm:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
for(var i=1;i<vm.allTextLines.length; i++){
let currentLinesValue = vm.allTextLines[i].split(',');
vm.uniqueAll.push(currentLinesValue);
for(var r =0; r < currentLinesValue.length; r++){
vm.arrayOfValuesOfFile.push(currentLinesValue[r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
First you should transform you bidimensional array into a one-dimension array.
var allTogether = []; // Array with all your CSV (no matter from which file it came from)
for (var i = 0; vm.allTextLines.length; i++) {
allTogether.push(vm.allTextLines[i]); // Gets the CSV line an adds to a one-dimension array
}
// Now you can iterate over the one-dimension array
for (var i = 0; allTogether.length; i++) {
var csvFields = allTogether[i].split(',');
// Here goes your code that works with the CSV fields.
}

Rearrange 2-dimensional array dynamically [duplicate]

This question already has answers here:
Swap rows with columns (transposition) of a matrix in javascript [duplicate]
(5 answers)
Javascript equivalent of Python's zip function
(24 answers)
Closed 8 years ago.
how to dynamically convert this type of array:
[
[a,b,c],
[d,e,f],
]
into
[
[a,d],
[b,e],
[c,f],
]
the length of the first array is not always the same size.
tried the following
for (var i = 0; i < multi.length; i++) { // 2
for (var j = 0; j < multi[i].length; j++) { // 3
multi2[j].push(multi[j][i])
}
}
it does not work
Two issues:
Initialize your multi2 subarray for i.
You have your i and j mixed up in the inner loop.
Here's a fiddle
var multi = [
["a","b","c"],
["d","e","f"],
["g","h","i"],
]
var multi2 = [];
for (var i = 0; i < multi.length; i++) { // 3
for (var j = 0; j < multi[i].length; j++) { // 3
multi2[j] = multi2[j]||[]; // initialize subarray if necessary
multi2[j].push(multi[i][j])
}
}

Handling multidimentional array in java script is not working

function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed

How to create a multi dimensional array in Javascript? [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 9 years ago.
How do you create a multi dimensional array in Javascript using a for loop ?
var test = [];
for(var i = 0; i < 100; i++){
test.push([i, "lol"]);
}
var sDataArray = MultiDimensionalArray(2, 2);
function MultiDimensionalArray(iRows, iCols) {
var i;
var j;
var table = new Array(iRows);
for (i = 0; i < iRows; i++) {
table[i] = new Array(iCols);
for (j = 0; j < iCols; j++) {
table[i][j] = "";
}
}
return (table);
}
var arr = [];
for(var i = 0;i<100;++i){
arr[i] = [];
for(var j = 0; j < 100; ++j){
arr[i][j] = i*j;
}
}
Its an array of arrays.
var arr = [
[0,1,2],
[3,4,5],
[
['a','b','c']
]
];

Compare arrays with jQuery [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Simplest code for array intersection in javascript
How to merge two arrays in Javascript
There are three arrays:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_new = Array();
First one is general, second is the items currenly in use. Third one includes all the items from the first array, witch are not mentioned in second.
How do I remove from the first array items, witch are used in second, and write the result to the third array?
We should get items_new = Array(523, 334, 5346). 3452 and 31 are removed, because they are mentioned in second array.
You could do this:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_compared = Array();
$.each(items, function(i, val){
if($.inArray(val, items_used) < 0)
items_compared.push(val);
});
That's it
Why not a simple for loop?
for(var j = 0; j < items.length; j++)
{
var found = false;
for(var k = 0; k < items_used.length; k++)
{
if(items_used[k] == items[j])
{
found = true;
break;
}
}
if(!found)
items_compared.push(items[j]);
}
As a faster solution maybe :
var j, itemsHash = {};
for (j = 0; j < items.length; j++) {
itemsHash[items[j]] = true;
}
for (j = 0; j < itemsUsed.length; j++) {
itemsHash[itemsUsed[j]] = false;
}
for (j in itemsHash) {
if (itemsHash[j]) {
itemsCompared.push(j);
}
}
runs in O(n) time, with a little more memory.
Basically I would make the third have all elements in the first, then loop through the second array removing all of those elements found in the first.
var items_compared = items;
for(int i = 0; i < items_used.length; ++i)
{
var indx = $.inArray(items_used[i], items_compared);
if(indx != -1)
items_compared.splice(indx, 1);
}

Categories

Resources