My approach
Define the return variable result
and its type. Since the array can be any data type of an object array, make the data type of the Record's property values to be typeof this[]
:
let result: Record<string, typeof this[]> = {};
Get the Array object using keyword this
:
console.log(this);
Iterate over the object array, calling the function fn
and pass the object element to get the object property as key.
fn(ele)
Check each element of the array, and if the key exists in the record result
, push that element into the property values of result
(the array with type typeof this
):
if(result[fn(ele)]) result[fn(ele)].push(ele);
If the key does not exist in the record "results", a new array is initialized with that element:
else result[fn(ele)] = [ele];
...
Array.prototype.groupBy = function(fn) {
let result: Record<string, typeof this[]> = {};
// console.log(this);
this.forEach(
ele => {
if(result[fn(ele)]) result[fn(ele)].push(ele);
else result[fn(ele)] = [ele];
}
);
return result;
}
Top comments (0)