How to split each element of an array of strings into different categories using Node.js?
Last Updated :
04 Apr, 2023
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 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.
JavaScript
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
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"]
]
Explore
Introduction & Installation
Node.js Modules , Buffer & Streams
Node.js Asynchronous Programming
Node.js NPM
Node.js Deployments & Communication
Resources & Tools