gpt4 book ai didi

javascript - 从 _.map() 返回唯一值

转载 作者:行者123 更新时间:2023-11-30 19:47:04 24 4
gpt4 key购买 nike

我已经使用下划线的 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

最佳答案

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

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

阅读有关 Set 的更多信息 here .

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

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

关于javascript - 从 _.map() 返回唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54846177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com