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) {
const chunks = [];
const index = 0;
for (let i = 0; i < array.length; i += split_size) {
let temp = array.slice(i, i + split_size);
chunks[categories[index]] = temp;
index++;
}
return chunks;
}
const input = [ 'abc' , 'def' , 'ghi' , 'jkl' , 'mno' , 'pqr' , 'stw' , 'xyz' ]
const categories = [ 'a' , 'b' , 'c' ]
const split_size = 3;
const output = split_array(input, categories, split_size);
console.log(output)
|
Output:
[
a: ["abc", "def", "ghi"]
b: ["jkl", "mno", "pqr"]
c: ["stw", "xyz"]
]