Sorting an array by chunks of 3 - javascript

Assume that you have an array and want to divide it by chunks of 3. If the array is..
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
...the new array would be
let newArr = [1, 4, 7, 10, 13, 2, 5, 8, 11, 3, 6, 9, 12]
// In other words:
1 2 3
4 5 6
7 8 9
10 11 12
13
The chunking part should be this code (if sorted like newArr):
let chunkedArr = _.chunk(_.toArray(newArr), 3);
...however I couldn't figure out how to sort the arr to newArr to be able to chunk in the right order. What is the proper way of handling such case?
Please note that the integers are just pseudo and I will use proper objects of array.

One option is to use ES6 reduce to group the array into a multidimensional array. Use concat to flatten the multidimensional array.
[].concat(...) - basically flattens the multidimensional array. Starting with an empty array [], you concat each secondary array. Use the spread operator (...) to reiterate each secondary array and concat each.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let groups = 3;
let newArr = [].concat(...arr.reduce((c, v, i) => {
let k = i % groups;
c[k] = c[k] || [];
c[k].push(v);
return c;
}, []));
console.log(newArr);

Please try the following (jsfiddle):
//This version works for variable chunk sizes as well.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
alert(chunks(arr, 3)); //You can update chunk size here
function chunks(arr, chunkSize) {
var result = [];
var index = 0;
for (var i = 0; i < chunkSize; i++) {
for (var j = 0; j < arr.length / chunkSize; j++) {
if (arr[i + (chunkSize * j)] != null)
result[index++] = arr[i + (chunkSize * j)];
}
}
return result;
}
//This version only works for chunks of size 3.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let subArr1 = [];
let subArr2 = [];
let subArr3 = [];
var result = [];
var i = 0, j = 0, k = 0;
for (var index = 0; index < arr.length; index++) {
if (index % 3 == 0) {
subArr1[i++] = arr[index];
}
if (index % 3 == 1) {
subArr2[j++] = arr[index];
}
if (index % 3 == 2) {
subArr3[k++] = arr[index];
}
}
result.push(subArr1, subArr2, subArr3);
alert(result);

Please check this it may help you. I also take a reference from here. Please check and let us know. any thing else you need.
Thanks
Here is the sample code.
var i,j,resArr,chunkSize = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
resArr = array.slice(i,i+chunk);
}

const original = [1,2,3,4,5,6,7,8,9,10,11,12,13]
const chunks = 3
function getChunckedArr(arr, n) {
let sub = new Array(n);
let result = [];
for (let i=0; i<sub.length; i++)
sub[i] = []
arr.forEach(function (val, index){
let o = (index % n);
sub[o][sub[o].length] = val;
});
for (let i=0; i<sub.length; i++)
result.push.apply(result, sub[i]);
return result;
}
const chunked = getChunckedArr(original, chunks);

Related

Trying to add each element of array to the next one for unknown number of elements

Something like this but generalized
let arr = [6, 5, 4, 3];
let i = 0, j = 0;
let result = [];
result.push(arr[0]+arr[1],
arr[2]+arr[3]);
console.log(result
Ignoring last element if array has odd number of elements:
function f(arr) {
let result = [];
for (let i=0; i<arr.length; i++) {
if (i % 2==0 && i<arr.length-1) {
result.push(arr[i] + arr[i+1]);
i++;
}
};
return result;
}
let arr = [6, 5, 4, 3];
console.log(f(arr));
console.log(f([1, 2, 3, 4, 5, 6, 7]));

Add every n items in an array

I have an array like so:
[5, 12, 43, 65, 34 ...]
Just a normal array of numbers.
What I wan't to do is write a function group(n, arr) which adds every n numbers in the array.
For example if I call group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) it should return
[
3 //1+2,
7 //3+4,
11 //5+6,
15 //7+8,
19 //9+10,
11 //whatever remains
]
I haven't tried anything yet, I will soon update with what I can.
You can use .reduce as follows:
function group(n, arr) {
// initialize array to be returned
let res = [];
// validate n
if(n > 0 && n <= arr.length) {
// iterate over arr while updating acc
res = arr.reduce((acc, num, index) => {
// if the current index has no remainder with n, add a new number
if(index%n === 0) acc.push(num);
// else update the last added number to the array
else acc[acc.length-1] += num;
// return acc in each iteration
return acc;
}, []);
}
return res;
}
console.log( group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) );
This approach features two loops, one for checking the outer index and anoter for iterating the wanted count of items for summing.
function group(n, array) {
const result = [];
let i = 0;
while (i < array.length) {
let sum = 0;
for (let j = 0; j < n && i + j < array.length; j++) {
sum += array[i + j];
}
result.push(sum);
i += n;
}
return result;
}
console.log(group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));
You could use Array.from to create the result array and then use its mapper to make the sums. These sums can be made by using reduce on the relevant slice of the array .
This is a functional programming solution:
const group = (step, arr) =>
Array.from({length: Math.ceil(arr.length/step)}, (_, i) =>
arr.slice(i*step, (i+1)*step).reduce((a, b) => a+b)
);
console.log(group(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));

Multiplying array numbers sequentially

The best and the easiest way to multiply array numbers sequentially
I have got an array with some values:
const arr = [1, 5, 12, 3, 83, 5];
Now I want to get the product of all values from arr. It should works like this: 1 * 5 * 12 * 3 * 83 * 5
I have tried with this code:
const arr = [1, 5, 12, 3, 83, 5];
multiply(arr);
function multiply(arr) {
for(i = 0; i < arr.length; i++) {
product = array[i] * array[i];
console.log(product);
}
}
This code above works like this: 1 * 1, 5 * 5, 12 * 12, 3 * 3, 83 * 83, 5 * 5 and that is not result that I need. I think I know why it works like this but I'm not sure how to write code that I need.
So what's the best option for this kind of tasks?
Edit.
For non-experienced people looking here in future this is the best option that we've found:
Leo Martin answer:
const array = [1, 5, 12, 3, 83, 5];
console.log(multiply(array)); // we log function return value
function multiply(array) {
let score = array[0];
for (i = 1; i < array.length; i++) {
score = score * array[i];
}
return score;
}
and also the shorter version:
By the way, you could use Array.reduce:
const array = [1, 5, 12, 3, 83, 5];
const result = array.reduce((acc, value, index) => {
if (index === 0) return value;
acc = acc * value;
return acc;
}, 0);
console.log(result);
Just move console.log outside for body:
const array = [1, 5, 12, 3, 83, 5];
console.log(multiply(array)); // we log function return value
function multiply(array) {
let score = array[0];
for (i = 1; i < array.length; i++) {
score = score * array[i];
}
return score;
}
By the way, you could use Array.reduce:
const array = [1, 5, 12, 3, 83, 5];
const result = array.reduce((acc, value, index) => {
if (index === 0) return value;
acc = acc * value;
return acc;
}, 0);
console.log(result);
You can use reduce method to multiply all numbers
const array = [1, 5, 12, 3, 83, 5];
const total = array.reduce((total,num) => total * num, 1);
console.log(total)
Corrected your program.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
var score = 1;
for(i = 0; i < array.length; i++) {
score = score * array[i];
}
console.log(score);
}
Hope the solution is self explanatory. Loop through array. Multiply each product and store the result in the same variable.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
let product = 1;
for(i = 0; i < array.length; i++) {
product *= array[i];
}
console.log(product);
}
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
var score = array[0];
for(i = 1; i < array.length; i++) {
score = score * array[i];
}
console.log(score);
}
var array = [1, 5, 12, 3, 83, 5];
var result = array.reduce(function(a, b) {
return a * b;
});
console.log(result);
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
for(i = 0; i < array.length-1; i++) {
score = array[i] * array[i+1];
console.log(score);
}
}
For the calculation of the final result of multiply:
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
score = 1;
for(i = 0; i < array.length; i++) {
score = score * array[ i ];
}
console.log(score); // expected result: 74700
}
Are you asking for a textual representation of the calculations? If so, use this:
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
score = '';
for(i = 0; i < array.length; i++) {
score += array[i].toString();
if ( i < array.length -1 ) score += '*';
}
console.log(score); // expected result: '1*5*12*3*83*5'
}
This should start to put you on the right way, hope it helps.
score = array[i] * array[i]; you are trying to multiply exact exp-rations.
const array = [1, 5, 12, 3, 83, 5];
its like: 1*1, 5*5
you can multiply array[i] * i
another approach might be an array function.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
let product = 1;
`enter code here`for(i = 0; i < array.length; i++) {
product *= array[i];
}
console.log(product);
}
let multiArray = array.map((num, index) => num *index)
console.log(multiArray)
for more info:https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Array/map.

How to transpose 2D square matrix stored as 1D array in Javascript

My question is closely related to this question but I'm looking for a solution in Javascript
How to Transpose 2D Matrix Stored as C 1D Array
Basically I have a 2D square matrix
1 2 3
4 5 6
7 8 9
Stored as follows
let anArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9]
How can I transpose this matrix so that the elements of my source array are switched as follows?
let newArray = [1, 4, 7, 2, 5, 8, 3, 6, 9]
You could take the length for the dimension of the array and map items on a specific index for a new array.
var array = [1 ,2, 3, 4, 5, 6, 7, 8, 9],
n = Math.sqrt(array.length),
transposed = array.map((_, i, a) => a[(i % n) * n + Math.floor(i / n)]);
console.log(transposed.join(' '));
The approach in the answer you linked to works well in JavaScript too.
For a 3 x 3:
const anArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArray = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
newArray[3 * i + j] = anArray[3 * j + i];
}
}
console.log(newArray);
For an N x N, just replace the 3's with N.
This answer avoids division and flooring (integer division) and a decent optimizer should make the code relatively fast. You might also consider initializing the new array with
let newArray = new Array(9);
or
let newArray = new Array(N * N);
but profile the code before attempting "optimizations" such as this.
var arr1 = [];
var arr2 = [];
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
arr1.push(mat[i][j]);
}
}
for(int j=0; j<mat[i].length; j++) {
for(int i=0; i<mat.length; i++) {
arr2.push(mat[i][j]);
}
}
Set a max "width" for your matrix and insert into a new array in loops, offset by 1 for each run.
function transpose(list, width) {
if (width === void 0) {
width = 1;
}
var t = 0;
var transposed = [];
while (t < width) {
for (var index = t; index < list.length; index += width) {
transposed.push(list[index]);
}
t++;
}
return transposed;
}
//TEST
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var transposed = transpose(list, 3);
console.log(list.join());
console.log(transposed.join());

Make nested array to group array elements

I have array:
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
Then I want to make group of 4 elements.
Every iteration, this array must be modified until it get's final face.
Step 1:
arr = [[1,2,3,4],5,6,7,8,9,10,11,12,13,14];
Step 2:
arr = [[1,2,3,4],[5,6,7,8],9,10,11,12,13,14];
Step 3:
arr = [[1,2,3,4],[5,6,7,8],[9,10,11,12],13,14];
Step 3:
arr = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14]];
How is this possible?
I tried this:
var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
var i,j,temparray,chunk = 4;
for (i=0,j=array.length; i<j; i+=chunk) {
temparray = array.slice(i,i+chunk);
console.log(temparray);
}
But I don't know then how to save this chunk into own array and not in the new array.
Using Array#reduce method.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
newArr = arr.reduce((acc, item, index) => {
if ((index) % 4 === 0) {
acc.push([item]);
} else {
acc[acc.length - 1].push(item);
}
return acc;
}, []);
console.log(newArr); // [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14 ] ]
You could splice the array until the length is smaller than the index of the last insertation.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
i = 0;
while (i < array.length) {
array.splice(i, 0, array.splice(i, 4));
console.log(JSON.stringify(array));
i++;
}
lodash probably has better performances than my implementation, but if you are looking to do so with vanilla javascript then you can like this (though many other ways are possible):
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
var newArr = arr.reduce((acc, val, idx)=>{
if(idx % 4 === 0){
acc.push([]);
}
acc[acc.length-1].push(val)
return acc
}, [])
console.log(newArr);
The lodash method chunk will do this for you.
result = _.chunk(arr, 4);
function chunkArray(myArray, chunk_size){
var index = 0;
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunk_size) {
myChunk = myArray.slice(index, index+chunk_size);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}
// Split in group of 3 items
var result = chunkArray([1,2,3,4,5,6,7,8], 3);
// Outputs : [ [1,2,3] , [4,5,6] ,[7,8] ]
console.log(result);
Just push it to the resulting array:
const chunk = 4, result = []
for (var i = 0, j = array.length; i < j; i += chunk) {
result.push(array.slice(i,i + chunk));
}
I thought it would be fun too if I add one more solution using recursive calls, Happy coding!
Test it here
function split(arr, offset, res){
//stop condition (offset exceeds len of array)
if(offset>arr.length)
return res;
//slice 4 elms
res.push(arr.slice(offset,offset+4));
//recursion
return split(arr, offset+4, res);
}
var res = split([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 0, []);
console.log(res);

Categories

Resources