Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```javascript
- function groupBy(array, callback) {
- let obj = {};
- let returnArray = [];
- // loop through array and perform callback on each element
- array.forEach(function(element) {
- // create array of return values
- let returnValue = callback(element);
- returnArray.push(returnValue);
- });
- // loop through each return value
- for (let i = 0; i < returnArray.length; i++) {
- // initialize property array
- let propertyArray = [];
- // loop through each element
- for (let j = 0; j < array.length; j++) {
- // if return of callback function equals return, then push element to property array
- if (callback(array[j]) === returnArray[i]) {
- propertyArray.push(array[j]);
- }
- }
- // assign property array to appropriate key
- obj[returnArray[i]] = propertyArray;
- }
- return obj;
- }
- // Uncomment these to check your work!
- const decimals = [1.3, 2.1, 2.4];
- const floored = function(num) { return Math.floor(num); };
- console.log(groupBy(decimals, floored)); // should log: { 1: [1.3], 2: [2.1, 2.4] }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement