Slice Array into an array of arrays - javascript

If I have a function:
function sliceArrayIntoGroups(arr, size) {
var slicedArray = arr.slice(0, size);
return slicedArray;
}
I am looking to take an array and slice it into an array of arrays.. how would I go about doing so?
So if I had this:
sliceArrayIntoGroups(["a", "b", "c", "d"], 2);
The result should be:
[["a","b"],["c","d"]]
But I don't know how to save the second part of the original array after slicing it.
Any help is appreciated.

The solution using regular while loop and custom step parameter:
function sliceArrayIntoGroups(arr, size) {
var step = 0, sliceArr = [], len = arr.length;
while (step < len) {
sliceArr.push(arr.slice(step, step += size));
}
return sliceArr;
}
console.log(sliceArrayIntoGroups(["a", "b", "c", "d"], 2));
console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 2));
console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3));
step option points to an offset of each extraction(slicing)

This ought to do it. It's a simple recursive function that slices n elements from the beginning of the array and calls itself with the remaining elements.
function sliceArrayIntoGroups(arr, size) {
if (arr.length === 0) { return arr; }
return [ arr.slice(0, size), ...sliceArrayIntoGroups(arr.slice(size), size) ];
}
console.log(sliceArrayIntoGroups([1,2,3,4,5], 2));
console.log(sliceArrayIntoGroups([1,2,3,4,5], 3));
console.log(sliceArrayIntoGroups([1,2,3,4,5], 10));

try this, it will slice origin array to 2 pieces, then concat to 1 array
function sliceArrayIntoGroups(arr, size) {
if (size >= arr.length || size <= 0) { return arr; }
return [arr.slice(0, size), arr.slice(size)];
}
console.log(sliceArrayIntoGroups(["a", "b", "c", "d"], 2));

Try this:
function sliceArrayIntoGroups(arr, size) {
var result = [];
while (arr.length > 0) {
result.push(arr.splice(0, size));
}
return result;
}
console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3));
console.log(sliceArrayIntoGroups(["a", "b", "c", "d"], 2));
function sliceArrayIntoGroups(arr, size) {
var result = [];
while (arr.length > 0) {
result.push(arr.splice(0, size));
}
return result;
}
This will divide array into pieces where each piece will be the size of size variable, so
sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3);
will output
[["a", "b", "c"], ["d", "e", "f"]]

Javascript slice() method returns the selected elements in an array, as a new array object. So using for loop create smallArray and push them to arrGroup array.
function sliceArrayIntoGroups(arr, size) {
let arrGroup =[];
for (let i=0; i<arr.length; i+=size) {
let smallArray = arr.slice(i,i+size);//creating smaller array of required size using slice
arrGroup.push(smallArray);
}
return arrGroup;
}

Reduce:
var x = [1,2,3,4,5,6,7,8,9];
var chunk = function(arr,n) {
var temp;
return arr.reduce(function(carry,item,index) {
//if we're at a chunk point: index%n == 0
if(!(index%n)) {
//if temp currently holds items, push it onto carry
if(temp && temp.length) { carry.push(temp); }
//reset temp to an empty array
temp = [];
}
//push the current item onto temp
temp.push(item);
//if this is the last item in the array, push temp onto carry
index == arr.length-1 && carry.push(temp);
return carry;
},[]);
};
chunk(x,5);

Related

Look into an array how many values are the same

So I trying to make a function for a slotmachine in javascript to look at 2 arrays and return a score on based on how many values are the same.
let testArray = ["a", "b", "c"];
let resultArray = ["a", "a", "c"];
let scoreCounter = 0;
let score = 0;
for (let i = 0; i < testArray.length; i++) {
for (let y = 0; y < resultArray.length; y++) {
if (resultArray[y] == testArray[i]) {
scoreCounter++
}
}
if (scoreCounter == 2) {
score = 200
} else if (scoreCounter == 3) {
score = 300
};
}
console.log(score)
// Return 3 times good => a,a,c are in the array.
I am trying to get this result:
If the player spins the wheel and get 0 same matches he gets 0 points
2 same matches = 200 points
3 same matches = 300 points
let testArray = ["a", "b", "c"];
let resultArray = ["a", "b", "c"]; // 0 points
let testArray = ["a", "b", "c"];
let resultArray = ["a", "a", "c"]; // 200 points
let testArray = ["a", "b", "c"];
let resultArray = ["a", "a", "a"]; // 300 points
How can I fix my loops to check for this result?
Group the array into an object whose keys are the values found, and whose values are the number of times a value has been found. Then call Math.max on the values of that object to get the maximum number of occurrences of any one element:
let resultArray = ["a", "a", "c"];
const grouped = {};
for (const item of resultArray) {
grouped[item] = (grouped[item] || 0) + 1;
}
const maxSameVals = Math.max(...Object.values(grouped));
const score = maxSameVals === 1
? 0
: maxSameVals * 100;
console.log(score);
You could count the values and then find the count by looking to the first array.
function getScore(left, right) {
let counts = {},
i = 0;
while (i < right.length) {
counts[right[i]] = (counts[right[i]] || 0) + 1;
i++;
}
return (counts[left.find(k => counts[k] > 1)] || 0) * 100;
}
console.log(getScore(["a", "b", "c"], ["a", "b", "c"]));
console.log(getScore(["a", "b", "c"], ["a", "a", "c"]));
console.log(getScore(["a", "b", "c"], ["a", "a", "a"]));

Function to reiterate values in an array using Javascript

I need to create a function that inputs a new value into an empty array, and then the value stays in the array, even if the value changes. Let me explain with an example and I have so far:
var arr = [];
arr.unshift("f");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("e");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("d");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("c");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("b");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("a");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("z");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
Here in the empty array a new value gets inputted in first position and stays in the array arr. This is what I get in the console:
(6) ["f"]
(6) ["e", "f"]
(6) ["d", "e", "f"]
(6) ["c", "d", "e", "f"]
(6) ["b", "c", "d", "e", "f"]
(6) ["a", "b", "c", "d", "e", "f"]
(6) ["z", "a", "b", "c", "d", "e"]
which is exactly what I want to achieve. Instead of these values I need a var that will get updated regularly.
var newValue = value_to_be_updated;
function myFunction(newValue) {
var arr = [];
arr.unshift(newValue);
return arr
}
if (arr.length > 6) {
arr.pop();
}
My goal is to reduce the above code and make it a function, but couldn't find anything helpful. Also is there any way the value inputted stays in the array, even if removed from the var?
Any help will be hugely appreciated!!!!!
Thanks in advance
You should be getting the new value dynamically using for example a prompt, if you are expecting the value of arr to remain the same after changing the source code that would not work.
Still has #gurvinder372 said your function should look something like this
var arr = [];
function myFunction(newValue) {
arr.unshift(newValue);
if (arr.length > 6) {
arr.pop();
}
return arr
}
then to use it you can do something like this
for (var i = 0; i<8; i++){
var value = prompt('enter char');
myFunction(value);
}

Trying to split array into specified amount of subarrays in javascript

I'm writing a function that takes an array and a number parameter and returns the number amount of arrays split from the given array. So the call chunkArrayInGroups(["a", "b", "c", "d"], 2); should return [a,b] [c,d]. My code is returning [a,c] [b,d]. It should be an easy solution, but I still can't figure out.
function chunkArrayInGroups(arr, size) {
// Break it up.
var newarr=[];
var amount=0;
if(arr.length%2===0)
{
amount=arr.length/size;
}
else
amount=(arr.length/size)+1;
console.log(amount);
for(i=0;i<amount;i++)
{
newarr[i]=[];
}
console.log(newarr);
for(z=0;z<arr.length;z=z+size)
{
for(x=0;x<size;x++)
{
newarr[x].push(arr[z+x]);
}
}
console.log(newarr);
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
Also, if you see bad syntax please correct me, I'm used to writing Java. Thank you!
Run over all the items in the array, and whenever the index % size is 0, add another sub array, then push the item to the last sub array.
function chunkArrayInGroups(arr, size) {
var chunks = [];
for(var i = 0; i < arr.length; i++) {
if(i % size === 0) {
chunks.push([]);
}
chunks[chunks.length - 1].push(arr[i]);
}
return chunks;
}
console.log('Size 2', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2)));
console.log('Size 3', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 3)));
console.log('Size 4', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 4)));
console.log('Size 6', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 6)));
You could use the Array.slice method together with the loop to chunk an array:
function chunkArrayInGroups(arr, size) {
let i,j,res = [];
for (i=0,j=arr.length; i<j; i+=size) {
res.push(arr.slice(i,i+size));
}
return res;
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
The issue comes from newarr[x].push(arr[z+x]);.
Each time the second loop runs, it adds 1 letter to the first array inside newarr and 1 letter to the second array inside newarr.
This is because x inside the loop (in the case of size = 2), starts as 0 (the first array) and then becomes 1 (the second array).
To fix this problem:
newarr[x].push(arr[z+x]); should be changed to newarr[z/size].push(arr[z+x]);
This would be my solution;
function chunkArrayInGroups(a,n){
return n > 0 ? n <= a.length ? a.reduce((r,e,i) => (r[Math.floor(n*i/a.length)].push(e),r), Array(n).fill().map(_ => [])) : a : a;
}
var a = ["a", "b", "c", "d","e"],
n = 3;
result = chunkArrayInGroups(a,n);
console.log(result);
Beside the given answers, you could use another approach with Array#reduce and check if you need a new array for a new chunk.
function chunkArrayInGroups(array, size) {
return array.reduce(function(r, a, i, aa) {
i % Math.ceil(aa.length / size) || r.push([]);
r[r.length - 1].push(a);
return r;
}, []);
}
console.log(chunkArrayInGroups(["a", "b", "c", "d", "e"], 3));

Removing Element From Array of Arrays with Regex

I'm using regex to test certain elements in an array of arrays. If an inner array doesn't follow the desired format, I'd like to remove it from the main/outer array. The regex I'm using is working correctly. I am not sure why it isn't removing - can anyone advise or offer any edits to resolve this problem?
for (var i = arr.length-1; i>0; i--) {
var a = /^\w+$/;
var b = /^\w+$/;
var c = /^\w+$/;
var first = a.test(arr[i][0]);
var second = b.test(arr[i][1]);
var third = c.test(arr[i][2]);
if ((!first) || (!second) || (!third)){
arr.splice(i,1);
}
When you cast splice method on an array, its length is updated immediately. Thus, in future iterations, you will probably jump over some of its members.
For example:
var arr = ['a','b','c','d','e','f','g']
for(var i = 0; i < arr.length; i++) {
console.log(i, arr)
if(i%2 === 0) {
arr.splice(i, 1) // remove elements with even index
}
}
console.log(arr)
It will output:
0 ["a", "b", "c", "d", "e", "f", "g"]
1 ["b", "c", "d", "e", "f", "g"]
2 ["b", "c", "d", "e", "f", "g"]
3 ["b", "c", "e", "f", "g"]
4 ["b", "c", "e", "f", "g"]
["b", "c", "e", "f"]
My suggestion is, do not modify the array itself if you still have to iterate through it. Use another variable to save it.
var arr = ['a','b','c','d','e','f','g']
var another = []
for(var i = 0; i < arr.length; i++) {
if(i%2) {
another.push(arr[i]) // store elements with odd index
}
}
console.log(another) // ["b", "d", "f"]
Or you could go with Array.prototype.filter, which is much simpler:
arr.filter(function(el, i) {
return i%2 // store elements with odd index
})
It also outputs:
["b", "d", "f"]
Your code seems to work to me. The code in your post was missing a } to close the for statement but that should have caused the script to fail to parse and not even run at all.
I do agree with Leo that it would probably be cleaner to rewrite it using Array.prototype.filter though.
The code in your question would look something like this as a filter:
arr = arr.filter(function (row) {
return /^\w+$/.test(row[0]) && /^\w+$/.test(row[1]) && /^\w+$/.test(row[2]);
});
jsFiddle
I'm assuming it is 3 different regular expressions in your actual code, if they are all identical in your code you can save a little overhead by defining the RegExp literal once:
arr = arr.filter(function (row) {
var rxIsWord = /^\w+$/;
return rxIsWord.test(row[0]) && rxIsWord.test(row[1]) && rxIsWord.test(row[2]);
});

How to split a long array into smaller arrays, with JavaScript

I have an array of e-mails (it can be just 1 email, or 100 emails), and I need to send the array with an ajax request (that I know how to do), but I can only send an array that has 10 or less e-mails in it. So if there is an original array of 20 e-mails I will need to split them up into 2 arrays of 10 each. or if there are 15 e-mails in the original array, then 1 array of 10, and another array of 5. I'm using jQuery, what would be the best way to do this?
Don't use jquery...use plain javascript
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var b = a.splice(0,10);
//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];
You could loop this to get the behavior you want.
var a = YOUR_ARRAY;
while(a.length) {
console.log(a.splice(0,10));
}
This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.
var size = 10; var arrayOfArrays = [];
for (var i=0; i<bigarray.length; i+=size) {
arrayOfArrays.push(bigarray.slice(i,i+size));
}
console.log(arrayOfArrays);
Unlike splice(), slice() is non-destructive to the original array.
Just loop over the array, splicing it until it's all consumed.
var a = ['a','b','c','d','e','f','g']
, chunk
while (a.length > 0) {
chunk = a.splice(0,3)
console.log(chunk)
}
output
[ 'a', 'b', 'c' ]
[ 'd', 'e', 'f' ]
[ 'g' ]
You can use lodash:
https://lodash.com/docs
_.chunk(['a', 'b', 'c', 'd'], 2);
// → [['a', 'b'], ['c', 'd']]
Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:
const chunkArray = (arr, size) =>
arr.length > size
? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
: [arr];
Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:
var longArray = []; // assume this has 100 or more email addresses in it
var shortArrays = [], i, len;
for (i = 0, len = longArray.length; i < len; i += 10) {
shortArrays.push(longArray.slice(i, i + 10));
}
// now you can iterate over shortArrays which is an
// array of arrays where each array has 10 or fewer
// of the original email addresses in it
for (i = 0, len = shortArrays.length; i < len; i++) {
// shortArrays[i] is an array of email addresss of 10 or less
}
Another implementation:
const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];
const size = 3;
const res = arr.reduce((acc, curr, i) => {
if ( !(i % size) ) { // if index is 0 or can be divided by the `size`...
acc.push(arr.slice(i, i + size)); // ..push a chunk of the original array to the accumulator
}
return acc;
}, []);
// => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]
NB - This does not modify the original array.
Or, if you prefer a functional, 100% immutable (although there's really nothing bad in mutating in place like done above) and self-contained method:
function splitBy(size, list) {
return list.reduce((acc, curr, i, self) => {
if ( !(i % size) ) {
return [
...acc,
self.slice(i, i + size),
];
}
return acc;
}, []);
}
As a supplement to #jyore's answer, and in case you still want to keep the original array:
var originalArray = [1,2,3,4,5,6,7,8];
var splitArray = function (arr, size) {
var arr2 = arr.slice(0),
arrays = [];
while (arr2.length > 0) {
arrays.push(arr2.splice(0, size));
}
return arrays;
}
splitArray(originalArray, 2);
// originalArray is still = [1,2,3,4,5,6,7,8];
I would like to share my solution as well. It's a little bit more verbose but works as well.
var data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var chunksize = 4;
var chunks = [];
data.forEach((item)=>{
if(!chunks.length || chunks[chunks.length-1].length == chunksize)
chunks.push([]);
chunks[chunks.length-1].push(item);
});
console.log(chunks);
Output (formatted):
[ [ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15 ] ]
You can start with an empty array and push inside it sections with your desired range from the original array at the same time you are subtracting from your original array until is empty.
const originalArr = [1,2,3,4,5,6,7,8,9,10,11];
const splittedArray = [];
while (originalArr.length > 0) {
splittedArray.push(originalArr.splice(0,range));
}
output for range 3
splittedArray === [[1,2,3][4,5,6][7,8,9][10,11]]
output for range 4
splittedArray === [[1,2,3,4][5,6,7,8][9,10,11]]
This is also good for a fronted pagination if want.
Another method:
var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var size = 2;
var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
.map(function() { return this.splice(0, size) }, longArray.slice());
// newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.
Another implementation, using Array.reduce (I think it’s the only one missing!):
const splitArray = (arr, size) =>
{
if (size === 0) {
return [];
}
return arr.reduce((split, element, index) => {
index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
return split;
}, []);
};
As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.
More compact:
const chunk = (xs, size) =>
xs.map((_, i) =>
(i % size === 0 ? xs.slice(i, i + size) : null)).filter(Boolean);
// Usage:
const sampleArray = new Array(33).fill(undefined).map((_, i) => i);
console.log(chunk(sampleArray, 5));
function chunkArrayInGroups(arr, size) {
var newArr=[];
for (var i=0; i < arr.length; i+= size){
newArr.push(arr.slice(i,i+size));
}
return newArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);
Using ES6 Generators
Late to the party, but ES6 generators opened up another neat way to achieve what is asked for.
/**
* Returns chunks of size n.
* #param {Array<any>} array any array
* #param {number} n size of chunk
*/
function* chunks(array, n){
for(let i = 0; i < array.length; i += n) yield array.slice(i, i + n);
}
const result = [...chunks([1, 2, 3, 4, 5, 6, 7, 8 , 9, 10], 3)];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Make it work for infinite Generators
Using the same idea you can create a generator which can also generate an infinite amount of n-sized chunks from values retrieved from another (possibly infinite) generator function. This can be very handy to lazy-generate values once they are required which significantly reduces the required memory or it can even be used to generate a possibly infinite/ unknown number of chunks.
Here an example which uses two generators.
nextNaturalNumber() is an infinite generator which always returns the next natural number. I am using the ES2020 bigint datatype here so there is no restriction (by JavaScript) for the size of the value.
chunksFromIterable() creates n-sized chunks from an possibly infinite iterable.
/**
* Returns chunks of size n for a possibly infinite iterator.
* n must be >= 1
* #param {Iterable<any>} iterable any array
* #param {number} n size of chunk for n >= 1
*/
function* chunksFromIterable(iterable, n){
let arr = [];
let i = n;
for (const value of iterable) {
if(i <= 0) {
// another chunk of size n is filled => return chunk
yield arr;
arr = []; // create new empty array
i = n;
};
arr.push(value);
i--;
}
// in case the iterable is not infinite check if there are still values in the array and return them if necessary
if(arr.length > 0) yield arr;
}
/**
* Infinite iterator which always gets the next natural number.
*/
function* nextNaturalNumber(){
let i = 0n;
while(true) {
i += 1n;
yield i;
}
}
console.log("Finite iterable:");
// this version can now be used using the for ... of loop
for(const threeNaturalNumbers of chunksFromIterable([1, 2, 3, 4, 5, 6, 7, 8 , 9, 10], 3)){
console.log(threeNaturalNumbers);
}
console.log("Infinite iterable:");
// and it can also be used for this infinite generator
for(const threeNaturalNumbers of chunksFromIterable(nextNaturalNumber(), 3)){
printBigIntArray(threeNaturalNumbers);
if(threeNaturalNumbers[0] > 30) break; // end here to avoid an infinite loop
}
// helper function to print array of bigints as this does not seem to be working for snippets
function printBigIntArray(arr){
console.log(`[${arr.join(", ")}]`);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can take a look at this code . Simple and Effective .
function chunkArrayInGroups(array, unit) {
var results = [],
length = Math.ceil(array.length / unit);
for (var i = 0; i < length; i++) {
results.push(array.slice(i * unit, (i + 1) * unit));
}
return results;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
Here is a simple one liner
var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
: (r.push([e]), r), []),
arr = Array.from({length: 31}).map((_,i) => i+1);
console.log(segment(arr,7));
as a function
var arrayChunk = function (array, chunkSize) {
var arrayOfArrays = [];
if (array.length <= chunkSize) {
arrayOfArrays.push(array);
} else {
for (var i=0; i<array.length; i+=chunkSize) {
arrayOfArrays.push(array.slice(i,i+chunkSize));
}
}
return arrayOfArrays;
}
to use
arrayChunk(originalArray, 10) //10 being the chunk size.
using recursion
let myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
let size = 4; //Math.sqrt(myArr.length); --> For a n x n matrix
let tempArr = [];
function createMatrix(arr, i) {
if (arr.length !== 0) {
if(i % size == 0) {
tempArr.push(arr.splice(0,size))
}
createMatrix(arr, i - 1)
}
}
createMatrix(myArr, myArr.length);
console.log(tempArr);
Note: The existing array i.e. myArr will be modified.
using prototype we can set directly to array class
Array.prototype.chunk = function(n) {
if (!this.length) {
return [];
}
return [this.slice(0, n)].concat(this.slice(n).chunk(n));
};
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].chunk(5));
let original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
let size = 5;
let fragments = Array.from(Array(Math.ceil(a.length / size))).map((_,index) => a.slice(index * size,(index + 1) * size))
If you want a method that doesn't modify the existing array, try this:
let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
let newArray = [];
let size = 3; // Size of chunks you are after
let j = 0; // This helps us keep track of the child arrays
for (var i = 0; i < oldArray.length; i++) {
if (i % size === 0) {
j++
}
if(!newArray[j]) newArray[j] = [];
newArray[j].push(oldArray[i])
}
function chunkArrayInGroups(arr, size) {
var newArr=[];
for (var i=0; arr.length>size; i++){
newArr.push(arr.splice(0,size));
}
newArr.push(arr.slice(0));
return newArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);
You can use the following code to achieve the required functionality
const splitter = (arr, splitBy, cache = []) => {
const tmp = [...arr]
while (tmp.length) cache.push(tmp.splice(0, splitBy))
return cache
}
const split = splitter([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21], 10)
console.log(split);
Notice, it was an array of length 22 then the splitter function splits it into 2 smaller arrays of 10 items and 1 array of 2 items.
let a = [1, 2, 3, 4, 6, 7, 8, 9, 10, 11];
let _splitCount = 3;
let b = a.reduce((acc, curr, index) => {
if (index % _splitCount === 0) {
acc.push([curr]);
} else {
acc[acc.length - 1].push(curr);
}
return acc;
}, []);
this is the easy solution i think❤️
You can use the below function if you know the number array (numGroups) to be split.
function createGroups(arr, numGroups) {
const perGroup = Math.ceil(arr.length / numGroups);
return new Array(numGroups)
.fill('')
.map((_, i) => arr.slice(i * perGroup, (i + 1) * perGroup));
}
Sample Use:
createGroups([0, 1, 2, 3, 4, 5, 6], 3); //arr = [0, 1, 2, 3, 4, 5, 6] and numGroups = 3

Categories

Resources