2

What is the fastest way to split an array into small chunks, then apply math function in the small array? The math function could be simple such as the total of the chunk mod 26.

What I mean, I have array [1,2,3,4,5,6], I need to create chunks of it to have every 3 elements in 1 chunk, so I will get from the main array:

[1,2,3] [4,5,6]

The apply total of [1,2,3] 6mod26, and [4,5,6] 15mod26. So, the final array will be [6,15]. Also, ignore the remaining of the main array if the remaining elements less the required chunk size, or add it in array alone.

simple way ..

[1,2,3,4,5,6,7] => chunk1[1,2,3] , chunk2[4,5,6] , chunk3[7]

result = [ (total([1,2,3]) mod 26 ) , (total([4,5,6]) mod 26 ) ]

I hope this is clear.

Marvix
  • 179
  • 3
  • 16
  • Splitting an array into chunks has been asked and answered many, many times: [Split array into chunks](https://stackoverflow.com/q/8495687/215552), [How to split a long array into smaller arrays, with JavaScript](https://stackoverflow.com/q/7273668/2155520), [Split JavaScript array in chunks using Lodash](https://stackoverflow.com/q/8566667/215552) – Heretic Monkey Apr 24 '20 at 19:53

2 Answers2

1

You could slice the array with the wanted size and reduce the array by adding all items and push the result of the remainder value.

var add = (a, b) => a + b,
    array = [1, 2, 3, 4, 5, 6],
    size = 3,
    result = [],
    i = 0;

while (i < array.length) {
     result.push(array.slice(i, i += size).reduce(add) % 26);
}

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Sorry, but I don't know how to make more clear than this, simple way: 1. chunk the array 2. get the total sum of each chunk 3. mod the total sum of each chunk 4. create a new array from the mod.

I reached to away, but I think there is a better way:

        splitArrayIntoChunksOfLen(arr, len) {
            let chunks = [], i = 0, n = arr.length;
            while (i < n) {
                chunks.push(arr.slice(i, i += len));
            }
            return chunks;
        }
let add = this.splitArrayIntoChunksOfLen(this.stringsArrays, 5)
                let newAdd = add.map(function (item) {
                    return item.reduce(function (acc, curr) {
                        acc += curr;
                        return acc - 92 * Math.floor(acc / 92);
                    }, 0)
                });
Marvix
  • 179
  • 3
  • 16