Write a function named groupBy
that will be used to extend the Array prototype and add grouping functionality to it.
The function will receive another function as a parameter - let's call it callback
.
The callback
will be called for each element of the Array, in order, and will return a value. Based on the returned value, the elements will be grouped in a Map, that's going to be returned by the groupBy
function.
Array.prototype.groupBy = groupBy;
const numbers = [1, 2, 3, 4, 5];
const groupingMap = numbers.groupBy(
(number) => number % 2 === 0 ? "even" : "odd"
);
console.log(groupingMap.get("even")); // [2, 4]
console.log(groupingMap.get("odd")); // [1, 3, 5]