Group Items on basis of name and Date Diff

问题描述 投票:0回答:1

Problem Statement

I am trying to group work experience on the basis of the company name which I am able to do. However, I want to group them only if they are consecutive jobs. The same logic LinkedIn has implemented.I think a recursive way of grouping items based on name and date difference is needed.for example

const data = [
    {
        Position: '1'
        CompanyName: 'Microsoft',
        StartDate: '2017-01-01',
        EndDate: '2017-04-01'
    },
    {
        Position: '2'
        CompanyName: 'Microsoft',
        StartDate: '2017-04-01',
        EndDate: '2017-10-01'
    },
        {
        Position: '3'
        CompanyName: 'Amazon',
        StartDate: '2017-10-01',
        EndDate: '2018-02-01'
    },
    {
        Position: '4'
        CompanyName: 'Microsoft',
        StartDate: '2018-03-04',
        EndDate: '2018-10-04'
    }
];

Currently, I am able to group by company name in node js using the following code

Code

/** applyGroupByPropName
* @param {Object} data this is the data object
* @param {string} propName This is the property to be grouped
* @returns {Object} returns a grouped object based on prop key
*/
    static applyGroupByPropName(data, propName) {
        if (!_.isNull(data) && !_.isEmpty(data) && data.length > 0) {
            data = _.mapValues(_.groupBy(data, propName),
                clist => clist.map(item => _.omit(item, propName)));
        }
        return data;
 }

and currently my output is like

   [ 
     CompanyName: 'Microsoft': [
     {
        Position: '1'   
        StartDate: '2017-01-01',
        EndDate: '2017-04-01'
    }, {
        Position: '2'
        StartDate: '2017-04-01',
        EndDate: '2017-10-01'
    }, {
        Position: '4'
        StartDate: '2018-03-04',
        EndDate: '2018-10-04'
    }
    ],
      CompanyName: 'Amazon' :
      [
        {
        Position: '3'
        StartDate: '2017-10-01',
        EndDate: '2018-02-01'
       }
      ]
   ]

Expected Output

   [ 
     CompanyName: 'Microsoft': [
     {
        Position: '1'   
        StartDate: '2017-01-01',
        EndDate: '2017-04-01'
    }, {
        Position: '2'
        StartDate: '2017-04-01',
        EndDate: '2017-10-01'
    }
    ],
      CompanyName: 'Amazon' :
      [
        {
        Position: '3'
        StartDate: '2017-10-01',
        EndDate: '2018-02-01'
       }
      ],
      CompanyName: 'Microsoft' :
      [
        {
        Position: '4'
        StartDate: '2018-03-04',
        EndDate: '2018-10-04'
       }
      ]
   ]

So Since position 4 is not the consecutive date it should not be grouped, Any ideas for this?I don't want to group if the date difference is more than a month.

javascript node.js group-by lodash
1个回答
1
投票

In pure JavaScript, I'll go with reduce to do the task. Also let me know if this do the required task.

© www.soinside.com 2019 - 2024. All rights reserved.