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

Running a Python script through a Javascript event

I'm looking to enhance my webpage by implementing a feature where users can generate a personalized QR code with the click of a button. My current setup involves a Python script that creates the QR code image and saves it as a .png file. I want to int ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

What could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

I am attempting to retrieve a value from a dropdown menu but I am encountering difficulties

Within the structure of a Vue component's template, I have the following code: <td> <select id="papel" @change="intervChange(row)"> <option value="Apreciador">Apreciar</option> <option value="Assessor">Assessor ...

Searching for multiple lines of text within a PHP document

Recently, I have been working on a project that involves an addon making modifications to a crucial system file. As part of this task, I have created a method to locate specific strings within the file: /** * @param $fileName * @param $str ...

Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared. Furthermore, according to this document from Google, a screen r ...

Fade in elements individually with the jQuery Waypoints plugin

I am currently using the waypoints jQuery plugin and it is functioning perfectly when fading in on scroll. However, I am facing an issue with making the blocks fade in individually one after the other. Here is the snippet of my jQuery code: $('.hbloc ...

What is the best way to locate an item reference for a specific DOM element?

Imagine a vast DOM structure with approximately 10,000 HTML elements, including 1,000 span tags. None of the span elements have any identifiers and are buried deep within other objects with long, complex Xpath paths that are not user-friendly for selectio ...

Tips for executing a callback function when triggering a "click" event in jQuery?

Having trouble triggering a custom event in the callback of a trigger call. Attempted solutions: var $input = $( ".ui-popup-container" ).find( "input" ).eq(2); function runtests () { console.log("clicked the input"); }; $input.trigger('click&ap ...

Using Javascript to create bold text within a string

I have noticed that many people are asking about this issue, but it seems like a clear and simple answer is hard to come by. Currently, I am working with Vue and trying to display text from an object in a component. My goal is to highlight the price port ...

How can I apply and delete a css class only while scrolling in a React application?

Currently, I am designing a pretend blog layout to showcase my work. The grid of posts features cards that are precisely 400x400 in size with a hover effect that magnifies and adds a drop shadow (this is visible in the dashboard route). However, an issue ...

What is the best way to generate a random string output from an object in JavaScript?

I'm struggling with extracting a random value from the object provided below, can anyone help me out? const hellos = { English: "Hello", Japanese: "Konnichiwa", German: "Hallo", Spanish: "Hola", Arabic: "Ah ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...

Matching only the specified Records in an array of Typescript generic objects

Check out this demo: https://tsplay.dev/Nnavaw I am working with an array that has the following structure: Array<{ id?: string; text?: string; date?: Date; }> This conflicts with the current implementation: data: Array<Par ...

Tips for troubleshooting when document.queryselector isn't functioning properly in NextJS for server-side rendering (SSR)

I encountered an issue with my circular progress bar code on a Next.js page. Whenever I try to update the "progressEndValue" variable to 67, it triggers a page refresh but doesn't reflect the new value on the progress bar. Instead, I receive the follo ...

Tips for retaining the value of a variable in JavaScript

I am a page that continuously redirects to itself, featuring next day and previous day arrows. Upon loading, the page always displays the new day. The days are stored in a localStorage as follows: for(var i = 0; i < status.length; i++) { local ...

Version 5 of angularfie2 is encountering an issue where the type 'Observable<{}[]>' cannot be assigned to the type 'Observable<any[]>'

Encountering an error while using angularfire2 version 5: The error reads: "Type 'Observable<{}[]>' is not assignable to type Observable < any [] >." Code snippet: exercisesList$: Observable <any[]>; ionViewDidLoad() { ...

What could be causing the returned promise value to not refresh?

I am currently facing an issue with my program. Upon clicking a button, the goal is to update the "likes" attribute of a MongoDB document that has been randomly fetched. Despite setting up the logic for this, the update does not occur as intended: MongoCli ...

Tap to navigate to queued sections on click

Greetings, community members! Despite my extensive research, I have been unable to find a solution to my query. Just a heads up - I am a novice when it comes to javascript and jQuery. My question pertains to incorporating two image buttons that, upon cli ...

Construction of jQuery Events

I have experience working with jquery tools and recently started exploring the twitter bootstrap src. One interesting thing I've observed is the utilization of the $.Event constructor for event triggering. For example, in cases like the bootstrap mo ...