[javascript] Array Partitioning by Length

slimdestro

D\sTro

Posted on October 15, 2020

[javascript] Array Partitioning by Length

Post #8

i am starting a new initiative today as "Building Custom Algorithm in Javascript without using inbuilt method"

i hope you guy will find this interesting. i will be writing a Polyfill/Vanilla of one javascript method everyday. starting today with a custom one

Algorithm : Partitioning array elements by range!
Workaround: [1, 2, 3, 4, 5, 6] should produce ["12", "34", "56"] or ["123", "456"] without using map() reduce() filter()

this is my implementation:
Note: always use arrow method. its not just a trend but it protects you from getting into severe undetectable bugs sometime.

Method 1 : using splice()

 let groupInString = (array, length)=>
    {   
        let newArr = []; init = 0;
        for(let i=0; i <= parseInt(array.length/length); i++){
            newArr.push(
                array.splice(init, length, null).join("")              
            );
            init++;
        }
        return newArr;
    }

// Testing:
groupInString([1, 2, 3, 4, 5, 6], 2); //["12", "34", "56"]
groupInString([1, 2, 3, 4, 5, 6], 3); //["123","456"]

Enter fullscreen mode Exit fullscreen mode

you can also try it on code pen here: Link

Method 2: Replicating same using slice()

let groupInString = (array, length)=>
    {   
        let newArr = []; init = 0;
        let lth = length;
        for(let i=0; i < parseInt(array.length/length); i++){
            newArr.push(
                array.slice(init, lth).join("")              
            );
            init = lth; lth += length;
        }
        return newArr;
    }
Enter fullscreen mode Exit fullscreen mode

thanks for catching the point @avalander

i will keep posting new scripts everyday and in case you have some algo you want it scripted(vanilla) then you can just comment it and i will post!

thanks for reading!

💖 💪 🙅 🚩
slimdestro
D\sTro

Posted on October 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related