Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so.

  groupBy: <Map>(predicate: (item: T) => Map[]) => Map[];

Array.prototype.groupBy = function (predicate) {
return this.reduce(
    (entryMap, e) => entryMap.set(e.status, [...entryMap.get(e.status) || [], e]),
    new Map()
)};

The predicate I am receiving in this method looks like ƒ (x) { return x.status; }.

I would like to replace e.status with something more generic so that I can use it like

arrayData.groupBy(x=>x.status)
. As a beginner, I am unsure of how to proceed. I came across a method in a post @ , shared by @Arthur Tacca

Thank you in advance

Answer №1

The code provided in the linked question is organizing the objects based on e.status. However, in your scenario, the property is dynamic. If you pass x => x.status as the predicate argument, how can you access the e.status for each object within the reduce function? Simply invoke the predicate with the e parameter instead of using e.status

Array.prototype.groupBy = function(predicate) {
  return this.reduce(
    (entryMap, e) => entryMap.set(predicate(e), [...entryMap.get(predicate(e)) || [], e]),
    new Map()
  )
};

const arr = [{ status: 10, id: 1 }, { status: 10, id: 2 }, { status:20, id: 3 }],
      map = arr.groupBy(e => e.status)

console.log(map.get(10))
console.log(map.get(20))
console.log(map.get(30))

It's important to remember that expanding native objects is considered a poor practice. Even if you extend prototypes with new items, ensure you do so using Object.defineProperty like shown below:

Object.defineProperty(Array.prototype, "groupBy", {
  value: function(predicate) {
    return this.reduce(
      (entryMap, e) => entryMap.set(predicate(e), [...entryMap.get(predicate(e)) || [], e]),
      new Map()
    )
  },
  configurable: true,
  writable: true
});

If you define it in this manner, enumerable will be set to false. Adding

Array.prototype.groupBy = function(predicate){}
directly will result in enumerable being set to true, causing it to be included in for..in loops.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Delete JavaScript functions and events from memory once the JavaScript code has been removed from the HTML file

I am encountering a situation with my website where popups loaded via ajax also load JavaScript code, which I want to remove when the popup is closed. The main site code looks like this: <body> ... <div id="popup" style="display:none"> < ...

What is the best way to trigger a useReducer dispatch function from a different file that is not a React component, without relying on Redux?

In my project, I have a function component that shows a game board named "EnemyBoardComponent.tsx" const enemyBoardReducer = (state:number[][], action:Action)=>{ switch(action.type){ case "update": { return EnemyBoard.getGrid(); ...

Tips for paginating a Laravel collection without using keys:

My task involves paginating an array of values with keys (e.g., 0,1,2) and extracting the values without their keys. Initially, the array looks like this: array:11 [ 0 => {#829 +"id": 2417 +"date": "2019-12-24 15:05:04" +"eventName": "At ...

Implementing NPM commands in Jenkins using shell scripting

Whenever I attempt to run the "npm" command, I encounter a syntax error. Users/Shared/Jenkins/Home/workspace/projectName/npm test ^^^^ SyntaxError: Unexpected identifier This is the Jenkins Build shel ...

Exploring the isolate scope within a compiled directive

I successfully managed to compile a directive using this piece of code: let element, $injector, $compile, link, scope; element = angular.element(document.getElementById(#whatever)); $injector = element.injector(); $compile = $injector.get('$compile& ...

When using Mongoose with Ejs, I am unable to view the comment I made when I navigate back to the post using GET. The comment only becomes visible after I have submitted it

After creating a comment, I can only see it when rendering the same page again. However, if I navigate to posts or myposts page and then return to the post where I created the comment, it disappears. Can someone please help me understand why this is happen ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

AngularJS toaster doesn't seem to be appearing

I have integrated the angularjs toaster library into my project. Here are the necessary references: https://github.com/jirikavi/AngularJS-Toaster Added the following references for the library: <link rel="stylesheet" href="bower_components/Angu ...

When the down key is pressed in a textarea, choose the list item

I have HTML similar to the following <div class="row"> <textarea id="txtArea" ng-model="input" ng-change="handleOnChange(input);getSearchField(input);" ng-click="search(input)" ng-focus="search(input);" ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

Loading SVG templates dynamically in Angular can be done by utilizing a string

Is it possible to convert SVG content loaded from a server into a component template in Angular, with the ability to bind properties to it? For example, <tspan [attr.color]="textColor" ...>{{myText}}</tspan>. I have tried loading and ...

Vue.js component mismatch in the layout

Attempting to set up a Vue application with vuetify while incorporating layouts. As a newcomer to Vue, I may have made some beginner errors. Here is the structure of my app: main.js // The Vue build version to load with the `import` command // (runtime- ...

Display temporary image until real image loads within ng-repeat angularjs

I am looking to display a placeholder image while the actual image is being loaded. I have tried using the ng-image-appear plugin. The issue I'm facing is that the placeholder image does not appear for img elements inside ng-repeat, although it works ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Encounter a Socket.io connection error due to net::ERR_CONNECTION_REFUSED when trying to access from multiple devices

I'm having trouble with other people's computers accessing my test chatting application. When they try to connect, they encounter this error: localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2Ko0C:1 Failed to ...

Adjust google maps to fill the entire vertical space available

I found this helpful resource for integrating Google Maps into my Ionic app. Everything is working smoothly, but I am trying to make the map fill the remaining height below the header. Currently, I can only set a fixed height in pixels like this: .angula ...

Slide in the Toggle Effect to Your Navigation Menu

Seeking help with enhancing my jQuery dropdown menu to include a slide down toggle effect similar to this example: http://jsfiddle.net/LaSsr/188/. Any assistance in applying this slide effect to the following JSfiddle would be greatly appreciated. Thank yo ...

How to update the state of a component in the root layout from its child components in Next JS 13 with the app router?

I am in the process of upgrading a Next JS app project to utilize the App Router. Within the layout.js (the root layout), there is a Logo component that will be visible on all routes. Within the RootLayout, I am managing a state variable to modify the ap ...

Scroll effect for read-only text input with long content inside a div

Is there a way to replicate the scroll functionality of a text input with readonly="readonly"? When the text exceeds the box size, you can highlight and scroll to view it all without a visible scrollbar. I am interested in achieving this effect within a p ...

The process of linking a Json response to a table

In my products.components.ts class, I am retrieving Json data into the variable this.Getdata. ngOnInit() { this._service.getProducts(this.baseUrl) .subscribe(data => { this.Getdata=data this.products=data alert(JSON.stringify(this.Getdata)); ...