Iterating over rows of 2-dimensional array containing arrays of different length - javascript

I have a function that picks all elements from a 2-dimensional array by its rows and returns a 1-dimensional array.
The array has a variable amount of columns and rows.
Example:
let arr = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
Returns:
[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12]
The function i came up with:
convertList = (list) => {
let result = [];
let listTotalEntries = R.sum(R.map(R.length)(list));
let mod = R.modulo(R.__, list.length);
let counterRow = -1;
for (let i = 0; i < listTotalEntries; i++) {
if (mod(i) === 0) {
counterRow++;
}
if (list[mod(i)][counterRow]) {
result.push(list[mod(i)][counterRow]);
console.log(list[mod(i)][counterRow]);
}
}
console.log(result);
return result;
};
Question: This function works only with square matrices - how can i make it work with a variable length of the contained arrays?
Example:
let arr = [
[1, 2],
[],
[9, 10, 11, 12]
];
Should return:
[1, 9, 2, 10, 11, 12]
Thanks for your help!
Muff

You had a ramda.js tag in here. With Ramda, it's pretty simple, since there are two functions that will help:
const convertList = compose(flatten, transpose);
convertList(arr); //=> [1, 9, 2, 10, 11, 12]
transpose flips a matrix over its main diagonal, that is, changing rows to columns and vice versa. flatten turns a list of lists into a plain list. So composeing like this essentially creates the equivalent of list => flatten(transpose(list)).
You can see this in action on the Ramda REPL.

I suggest to go step-by-step through the arrays
var arr1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
arr2 = [[1, 2], [], [9, 10, 11, 12]];
function single(array) {
var r = [],
max = Math.max.apply(null, array.map(function (a) { return a.length; })),
i = 0, j,
l = array.length;
while (i < max) {
for (j = 0; j < l ; j++) {
i in array[j] && r.push(array[j][i]);
}
i++;
}
return r;
}
document.write('<pre>' + JSON.stringify(single(arr1), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(single(arr2), 0, 4) + '</pre>');

Did you try this simple one?
var singleDimensionArr = arr.reduce(function(prev,current){return prev.concat(current)});
For example
[
[1, 2],
[],
[9, 10, 11, 12]
].reduce(function(prev,current){return prev.concat(current)});
outputs [1, 2, 9, 10, 11, 12]
Edit:
Based on the inputs from OP below, since the concatenation needs to happen column wise
var max = Math.max.apply(null, arr.map(function (a) { return a.length; }));
var finalArr = []; for( var i = 0; i < max; i++)
{
for( var j = 0; j < arr.length; j++)
{
arr[j][i] ? finalArr.push(arr[j][i]) : "";
}
}
console.log(arr);

This example makes a big sparse array putting each item where it would belong if the array were square. Then it filters out null values which occur where no input item was present.
let arr = [
[1, 2],
[],
[9, 10, 11, 12]
];
var out = arr.reduce(function(o,n,i,a) {
for (var j=0;j<n.length;j++){
o[a.length * j + i] = n[j];
}
return o;
},[]).filter(function(n) {
return n !== null;
});
alert(JSON.stringify(out));

Related

In a loop that results in several arrays, how to return an array with the sum of all of them

I have an array of strings that, after a lot of effort, I have managed to turn into several arrays with a loop. So right now, the loop is giving me something like:
[4,5,6,7,8]
[4,5,6,7,8],[1,2,3,4,5]
[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]
If I place the return lower in the code, I get:
[[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]]
What I need is the vertical sum of these arrays, so in this case it'd be:
[27,40,53,66,80]
So far, I'm usign '.push'. Also, console.log gives me this answer but return results in 'undefined'. Any help with these two things would be welcome!
----UPDATE----
As someone here suggested, I tried this but it doesn't work entirely:
array=[ [ 1, 2, 4 ], [ 4, 1, 5 ], [ 0, 5, 2 ] ];
let adding=0
const result=[]
for (let i = 0; i < array[0].length; ++i) {
for (let j = 0; j < array.length; ++j) {
adding += array[j][i];
}
result.push(adding);}
console.log(result)
```
The ouput is: [ 5, 13, 24 ] instead of [5,8,11]
1) You can easily achieve the result using map and reduce
const arr = [
[4, 5, 6, 7, 8],
[1, 2, 3, 4, 5],
[22, 33, 44, 55, 66],
];
const result = arr[0].map((_, i) => arr.reduce((acc, curr) => acc + curr[i], 0));
console.log(result)
2) Using simple for loops
const arr = [
[4, 5, 6, 7, 8],
[1, 2, 3, 4, 5],
[22, 33, 44, 55, 66],
];
const result = [];
for (let i = 0; i < arr[0].length; ++i) {
let sum = 0;
for (let j = 0; j < arr.length; ++j) {
sum += arr[j][i];
}
result.push(sum);
}
console.log(result);

Cant copy elements of 2D array into another array using for loop [duplicate]

This question already has answers here:
Create copy of multi-dimensional array, not reference - JavaScript
(4 answers)
Closed 1 year ago.
What's wrong with this code?
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = []; // or arr = [[]];
for (let i = 0; i < matrix1.length; i++) {
for (let j = 0; j < matrix1[i].length; j++) {
arr[i][j] = matrix1[i][j];
}
}
console.log(arr);
Error is:
Cannot set property '0' of undefined
This is when I try to assign the value of an element of matrix1 to the new array.
for loop works for the single dimensional array.
try this
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = []; // or arr = [[]];
for (let i = 0; i < matrix1.length; i++) {
for (let j = 0; j < matrix1[i].length; j++) {
if(!arr[i])
arr[i] = []
arr[i][j] = matrix1[i][j];
}
}
if you want copy a 2d array without for loop try this one:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = JSON.parse(JSON.stringify(matrix1))
You need to create a new sub array in the outer loop so that arr[i] is an array and not undefined
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = [];
for (let i = 0; i < matrix1.length; i++) {
// push a new sub array to be populated in next loop
arr.push([]);
for (let j = 0; j < matrix1[i].length; j++) {
arr[i][j] = matrix1[i][j];
}
}
console.log(arr);
The problem is the line arr[i][j] = matrix1[i][j];, since arr[i][j] is undefined at this point.
The correct way of adding elements to an array is using the .push() function:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = [];
for (let i = 0; i < matrix1.length; i++) {
arr.push([]);
for (let j = 0; j < matrix1[i].length; j++) {
arr[i].push(matrix1[i][j]);
}
}
console.log(arr);
Also note that using JSON might achieve the same task in a simpler way:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = JSON.parse(JSON.stringify(matrix1))
console.log(arr)

Why JS is passing a number into the array as a string?

I'm trying to obtain // [2,6,0,8,4] from the function:
let getValidPassword = arr => {
let x = [];
for (let i in arr) {
for (let j in arr[i]) {
if (arr[i][j] % 2 !== 0) {
break;
} else {
x += arr[i][j];
}
}
}
return x
};
var loggedPasscodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3]
];
console.log(getValidPassword(loggedPasscodes));
However when I run the typeof x, I'm getting a string(I though it was a number) and when I print x I get 26084 instead of [26084]
what witchcraft is this?
I though setting x to [ ] would make the trick...
thank you.
The problem here is that you have declared x=[] but you are modifying it as x += arr[i][j]; as soon as javascript gets to this line. It treats the array as string calling x.toString() internally and appending to that string. For example if you declare an array as a=[] and call a+=1 then a will become "1". In javascript everything is value typed, it doesn't matter what you declare when you assign some value to it or do some operation on the variable, it gets converted to the type of value.
I would recommend you to go through this
let getValidPassword = arr => {
let x = [];
let temp = [];
for (let i in arr) {
for (let j in arr[i]) {
if (arr[i][j] % 2 !== 0) {
break;
} else {
temp.push(arr[i][j]);
}
if(temp.length == arr[i].length)
x = temp.slice();
}
}
return x
};
var loggedPasscodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3]
];
console.log(getValidPassword(loggedPasscodes));
The problem is that you are incrementing your variable, to add an element to an array you need to use the push() method.
Correct code:
let getValidPassword = arr => {
let x = [];
for (let i in arr) {
for (let j in arr[i]) {
if (arr[i][j] % 2 !== 0) {
break;
} else {
x.push(arr[i][j]);
}
}
}
return x
};
var loggedPasscodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3]
];
console.log(getValidPassword(loggedPasscodes));
When you concatenate an array (which is what += is doing) it first converts the array and the value being appended to strings.
In order to add elements to the x array use x.push(arr[i][j]), this will insert them without type conversion.

Javascript Basic Logic - print each three and four cycle from 1 to n

I want to see the output like
[0, 1, 2]
[3, 4, 5, 6]
[7, 8, 9]
[10, 11, 12, 13]
[14, 15, 16]
...
recognize every three(a cycle) and four(b cycle) to do something.
I have only figure out some bad way I think like following:
var arr = [];
function a(n) {
var eachCycle = 7;
var aCycle = 3;
var bCycle = 0;
arr.push(0);
for (var i = 1; i < n; i += 1) {
if (i % eachCycle === aCycle || i % eachCycle === bCycle) {
if(i % eachCycle === aCycle) {
// print three column
} else if(i % eachCycle === bCycle) {
// print four column
}
console.log(arr);
arr.length = 0;
}
arr.push(i)
}
}
is there any good idea to improve this function for the output !?
Thanks
How about this:
function a(n)
{
// keep track of all the cycles
var total = [];
// hold values for the current cycle
var temp = [];
// cycle sizes
var cycleSizes = [3, 4];
// index of the current cycle
var currentCycleIndex = 0;
// iterate through numbers
for(var i = 0; i < n; ++i)
{
// push the value into the temp
temp.push(i);
// if the length of the temp array is the length we want for the current cycle then
if(temp.length == cycleSizes[currentCycleIndex])
{
// save the cycle data
total.push(temp);
// reset the cycle
temp = [];
// change the cycle
currentCycleIndex = currentCycleIndex ^ 1;
}
}
return total;
}
a(9);
[
[0, 1, 2],
[3, 4, 5, 6],
[7, 8]
];
a(17);
[
[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],
[10, 11, 12, 13],
[14, 15, 16],
];

How to sum elements at the same index in array of arrays into a single array?

Let's say that I have an array of arrays, like so:
[
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
]
How do I generate a new array that sums all of the values at each position of the inner arrays in javascript? In this case, the result would be: [17, 10, 19]. I need to be able to have a solution that works regardless of the length of the inner arrays. I think that this is possible using some combination of map and for-of, or possibly reduce, but I can't quite wrap my head around it. I've searched but can't find any examples that quite match this one.
You can use Array.prototype.reduce() in combination with Array.prototype.forEach().
var array = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
],
result = array.reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Update, a shorter approach by taking a map for reducing the array.
var array = [[0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3]],
result = array.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), []);
console.log(result);
Using Lodash 4:
function sum_columns(data) {
return _.map(_.unzip(data), _.sum);
}
var result = sum_columns([
[1, 2],
[4, 8, 16],
[32]
]);
console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
For older Lodash versions and some remarks
Lodash 4 has changed the way _.unzipWith works, now the iteratee gets all the values passed as spread arguments at once, so we cant use the reducer style _.add anymore. With Lodash 3 the following example works just fine:
function sum_columns(data) {
return _.unzipWith(data, _.add);
}
var result = sum_columns([
[1, 2],
[4, 8, 16],
[32],
]);
console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
_.unzipWith will insert undefineds where the row is shorter than the others, and _.sum treats undefined values as 0. (as of Lodash 3)
If your input data can contain undefined and null items, and you want to treat those as 0, you can use this:
function sum_columns_safe(data) {
return _.map(_.unzip(data), _.sum);
}
function sum_columns(data) {
return _.unzipWith(data, _.add);
}
console.log(sum_columns_safe([[undefined]])); // [0]
console.log(sum_columns([[undefined]])); // [undefined]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
This snipet works with Lodash 3, unfortunately I didn't find a nice way of treating undefined as 0 in Lodash 4, as now sum is changed so _.sum([undefined]) === undefined
One-liner in ES6, with map and reduce
var a = [ [0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3] ];
var sum = a[0].map((_, i) => a.reduce((p, _, j) => p + a[j][i], 0));
document.write(sum);
Assuming that the nested arrays will always have the same lengths, concat and reduce can be used.
function totalIt (arr) {
var lng = arr[0].length;
return [].concat.apply([],arr) //flatten the array
.reduce( function(arr, val, ind){ //loop over and create a new array
var i = ind%lng; //get the column
arr[i] = (arr[i] || 0) + val; //update total for column
return arr; //return the updated array
}, []); //the new array used by reduce
}
var arr = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
];
console.log(totalIt(arr)); //[17, 10, 19]
Assuming array is static as op showned.
a = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
]
b = []
for(i = 0; i < a[0].length; i++){
count = 0
for(j = 0; j < a.length; j++){
count += a[j][i]
}
b.push(count)
}
console.log(b)
So far, no answer using the for ... of mentioned in the question.
I've used a conditional statement for different lengths of inner arrays.
var a = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
];
i = 0;
r = []
for (const inner of a) {
j = 0;
for (const num of inner) {
if (j == r.length) r.push(num)
else r[j] += num
j++;
}
i++;
}
console.log(r);
True, in this case, the classic for cycle fits better than for ... of.
The following snippet uses a conditional (ternary) operator.
var a = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
];
r = [];
for (i = 0; i < a.length; i++) {
for (j = 0; j < a[i].length; j++) {
j==r.length ? r.push(a[i][j]) : r[j]+=a[i][j]
}
}
console.log(r);
A solution using maps and reductions, adding elements from different lengths of arrays.
var array = [
[0],
[2, 4],
[5, 5, 7, 10, 20, 30],
[10, 0]
];
b = Array(array.reduce((a, b) => Math.max(a, b.length), 0)).fill(0);
result = array.reduce((r, a) => b.map((_, i) => (a[i] || 0) + (r[i] || 0)), []);
console.log(result);
const ar = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
]
ar.map( item => item.reduce( (memo, value)=> memo+= value, 0 ) )
//result-> [4, 12, 17, 13]

Categories

Resources