Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 27 Jun, 2021

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

Example:

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

Output :

          a: [ ‘abc’, ‘def’, ‘ghi’ ],



         b: [ ‘jkl’, ‘mno’, ‘pqr’ ],

        c: [ ‘stw’, ‘xyz’ ] 

]

Approach:

  • Initialize an object that will store the categories in it and also initialize a variable index which 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.

Javascript




function split_array (array, categories, split_size) {
    // Initialize empty array
    var chunks = [];
     
    // Initialize index equal to zero to keep track of categories
    var index=0;
     
    // Traverse the array according to the split size
    for(var i=0; i<array.length; i+=split_size){
        // Slicing the split_size array from i
        var 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
        index++;
    }
 
    // 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

Output:

[
    a: ["abc", "def", "ghi"]
    b: ["jkl", "mno", "pqr"]
    c: ["stw", "xyz"]
]
My Personal Notes arrow_drop_up
Recommended Articles
Page :