Open In App
Related Articles

How to split each element of an array of strings into different categories using Node.js?

Improve Article
Save Article
Like Article

The task is to split each element of a string array into different categories.


Input Array :  const input = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stw', 'xyz']

Category Array :  const categories = ['a', 'b', 'c']

Split Size :  const split_size = 3

    a: [ 'abc', 'def', 'ghi' ],
    b: [ 'jkl', 'mno', 'pqr' ],
    c: [ 'stw', 'xyz' ] 


  • Initialize an object that will store the categories in it and also initialize a variable index that will keep the index of the categories.
  • Start traversing the array and split it according to the split size.
  • Assign the new split array to the given category and increment the index.

The code for the above approach is given below.


function split_array(array, categories, split_size) {
    // Initialize empty array
    const chunks = [];
    // Initialize index equal to zero to keep track of categories
    const index = 0;
    // Traverse the array according to the split size
    for (let i = 0; i < array.length; i += split_size) {
        // Slicing the split_size array from i
        let temp = array.slice(i, i + split_size);
        // Assigning the sliced array to the category
        chunks[categories[index]] = temp;
        // Increment index to keep track of categories
    // return the final array
    return chunks;
//input array
const input = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stw', 'xyz']
//categories array
const categories = ['a', 'b', 'c']
const split_size = 3; //split size
//calling the function
const output = split_array(input, categories, split_size);
console.log(output) //printing the array


    a: ["abc", "def", "ghi"]
    b: ["jkl", "mno", "pqr"]
    c: ["stw", "xyz"]
Last Updated : 04 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials