In: Computer Science
Hi, i need to generate into groups the array.For example:
([ 'a', 'b', 'c', 'd' ], 2)=>[ [ 'a', 'b' ], [ 'c', 'd' ] ]
([ { id: 5 }, { id: 10 }, { id: 20 } ], 2)=>. ([ [ { id: 5 }, { id: 10 } ], [ { id: 20 } ] ])
In javascript please
utils={ }
utils.generateGroups = () => { | |
// INPUT arguments | |
// - A 1-dimensional array | |
// - The length of each subgroup that should be created | |
// | |
// RETURN value | |
// - A 2-dimensional array of arrays. Each subarray should be as long as the length argument passed in to the function, except for the final subarray, which can be shorter and contain a "remainder" smaller than that length. | |
// | |
//your code here | |
}; |
Code
utils = {}
utils.generateGroups = (arr, size) => {
// INPUT arguments
// - A 1-dimensional array
// - The length of each subgroup that should be created
//
// RETURN value
// - A 2-dimensional array of arrays. Each subarray should be as long as the length argument passed in to the function, except for the final subarray, which can be shorter and contain a "remainder" smaller than that length.
//
let newarr = [], finalArr = []
for (let i = 0; i < arr.length; i++) {
if (newarr.length < size) {
newarr.push(arr[i])
}
else {
finalArr.push(newarr)
newarr = [arr[i]]
}
}
finalArr.push(newarr)
return finalArr
};
console.log(utils.generateGroups(['a', 'b', 'c', 'd'], 2))
console.log(utils.generateGroups([ { id: 5 }, { id: 10 }, { id: 20 } ], 2))
Screenshot
Output