skip to Main Content

Code:

var dataArray: { rootCause: string, countermeasure?: any, signalName: any, importance: any }[] = []
dataArray.push({
            rootCause: x.description,
            countermeasure: response.countermeasures[ii],
            signalName: x.signalName,
            importance: x.importance
          })
const result = dataArray.group((data: any) => data.rootCause);

I`m just having an array of objects, and group method is for array itself.

Error:

TS2339: Property 'group' does not exist on type '{ rootCause: string; countermeasure?: any; signalName: any; importance: any; }[]'.

In the above code, group method is underlined with the red color.

Official docs to check its working click me

In there, its mentioned that its an experimental one, not sure if we could use it or not.
enter image description here

Similar question click me to what I asked, but mine is not solved.

I made an example code to try out group() on https://onecompiler.com/javascript/, though in the compiler it says "group is not function" :
enter image description here
By this should I conclude that we cant use group method for array?

2

Answers


  1. Chosen as BEST ANSWER

    Alright, So official group() method is not working as intended. Check it out here

    But we could have our own walkaround for it.

    Let say the data that we have is as follows:

    const products = [
      { name: 'apples', category: 'fruits' },
      { name: 'oranges', category: 'fruits' },
      { name: 'potatoes', category: 'vegetables' }
    ];
    

    Required output:

    const groupByCategory = {
      'fruits': [
        { name: 'apples', category: 'fruits' }, 
        { name: 'oranges', category: 'fruits' },
      ],
      'vegetables': [
        { name: 'potatoes', category: 'vegetables' }
      ]
    };
    

    Code:

    const groupByCategory = products.reduce((group, product) => {
      const { category } = product;
      group[category] = group[category] ?? [];
      group[category].push(product);
      return group;
    }, {});
    
    console.log(groupByCategory);
    

    ScreenShot of the output : enter image description here For more detailed information check here .


  2. enter image description here

    This is only available for safari and safari on IOS.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search