SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ```javascript
  2. function groupBy(array, callback) {
  3.   let obj = {};
  4.   let returnArray = [];
  5.   // loop through array and perform callback on each element
  6.   array.forEach(function(element) {
  7.     // create array of return values
  8.     let returnValue = callback(element);
  9.     returnArray.push(returnValue);
  10.   });
  11.  
  12.   // loop through each return value
  13.   for (let i = 0; i < returnArray.length; i++) {
  14.     // initialize property array
  15.     let propertyArray = [];
  16.     // loop through each element
  17.     for (let j = 0; j < array.length; j++) {
  18.       // if return of callback function equals return, then push element to property array
  19.       if (callback(array[j]) === returnArray[i]) {
  20.         propertyArray.push(array[j]);
  21.       }    
  22.     }
  23.     // assign property array to appropriate key
  24.     obj[returnArray[i]] = propertyArray;
  25.   }
  26.   return obj;
  27. }
  28. // Uncomment these to check your work!
  29. const decimals = [1.3, 2.1, 2.4];
  30. const floored = function(num) { return Math.floor(num); };
  31. console.log(groupBy(decimals, floored)); // should log: { 1: [1.3], 2: [2.1, 2.4] }
  32. ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top