从_.map()

时间:2019-02-23 21:02:05

标签: javascript underscore.js

我已经使用下划线的groupBy对数据集合进行了分组,但是当我映射分组后的数据时,就会出现重复:

var data = [];
for (var i = 1; i < (allTextLines.length - 1); i++){
    var obj = {};
    var allTextLine = allTextLines[i].split(',');
    obj["date"] = allTextLine[headerColumnIndexMap[requiredHeaders[1]]];
    obj["servingTime"] = allTextLine[headerColumnIndexMap[requiredHeaders[2]]];
    obj["replacement"] = allTextLine[headerColumnIndexMap[requiredHeaders[3]]];
    obj["fullname"] = allTextLine[headerColumnIndexMap[requiredHeaders[4]]];
    obj["center"] = allTextLine[headerColumnIndexMap[requiredHeaders[5]]];
    obj["products"] = allTextLine[headerColumnIndexMap[requiredHeaders[6]]];


    data.push(obj);

}


var groups = _.groupBy(data, function(v){
                    return [v.date, v.servingTime, v.replacement];
                });

var grouped = _.map(groups, function(group){
                    return {
                        date : group[0].date,
                        servingTime : group[0].servingTime,
                        replacement : group[0].replacement,
                        children: _.map(group, function(f){
                            return [f.fullname, f.center];
                        }),
                        products: _.map(group, 'products'),
                        units : _.map(group, 'fullname').length

                    };
                });

问题是如何从子代和产品结果中删除重复项?我已经尝试链接并使用.unique()。value(),但是它不起作用...

var grouped = _.map(groups, function(group){
                    return {
                        date : group[0].date,
                        servingTime : group[0].servingTime,
                        replacement : group[0].replacement,
                        children: _.chain(group).map(group, function(f){
                            return [f.fullname, f.center];
                        }).uniq().value(),
                        products: _.map(group, 'products'),
                        units : _.map(group, 'fullname').length

                    };
                });

这是调试器中显示的结果:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用简单的Set-不允许重复:

products: Array.from(new Set(_.map(group, "products"))),

详细了解Set here

或者,在您的filter的末尾添加一个_.map

products: _.map(groups, "products").filter((e, i, a) => a.indexOf(e) == i),