Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

The value associated with each key will be an array consisting of all the elements that resulted in that return value when passed into the callback.

function groupBy(array, callback) {

  return array.reduce((acc,cur) => {
    let key = callback(cur)
    acc[key] = acc[key] || [];
    acc[key].push(cur)
    return acc;
  },{})
  
}

const decimals = [1.3, 2.1, 2.4];

const floored = function(num) {
  return Math.floor(num);
};

console.log(groupBy(decimals, floored));
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #The #key #array #consisting #elements #resulted #return #passed
ADD COMMENT
Topic
Name
8+5 =