Suppose, we have an array of Numbers represented by strings like this −
const arr = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];
We are required to write a JavaScript function that takes in one such array and groups all the strings starting with same number in a common subarray.
Therefore, the output of our function should look like −
const output = [["1.1","1.2","1.3"],["2.1","2.2"],["3.1","3.2","3.3"],["4.1","4.2"]];
Example
The code for this will be −
const arr = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"]; const groupSimilarStarters = arr => { let res = []; res = arr.reduce((acc, val, ind) => { const firstChar = el => { return (el || '').split('.')[0]; } if(firstChar(val) === firstChar(arr[ind - 1])){ acc[acc.length - 1].push(val); }else{ acc.push([val]); }; return acc; }, []); return res; } console.log(groupSimilarStarters(arr));
Output
The output in the console −
[ [ '1.1', '1.2', '1.3' ], [ '2.1', '2.2' ], [ '3.1', '3.2', '3.3' ], [ '4.1', '4.2' ] ]