我需要创建一个包含2列结果的组,并按名称和列的大小分隔。
示例:表格基础
Name | Size | Item
Frankincense | 5ml | 1562
Frankincense | 10ml | 1563
Frankincense | 15ml | 1564
Geranium | 5ml | 1565
Geranium | 10ml | 1566
Geranium | 15ml | 1567
Ginger | 5ml | 1568
Ginger | 10ml | 1569
Ginger | 15ml | 1570
Grapefruit | 5ml | 1571
Grapefruit | 10ml | 1572
Grapefruit | 15ml | 1573
Lavender | 5ml | 1574
Lavender | 10ml | 1575
Lavender | 15ml | 1576
示例:表格结果
Name/Size | 5ml | 10ml | 15ml
Frankincense | 1562 | 1563 | 1564
Geranium | 1565 | 1566 | 1567
Ginger | 1568 | 1569 | 1570
Grapefruit | 1571 | 1572 | 1573
Lavender | 1574 | 1575 | 1576
我发现了一些东西,但还没有结果。我需要对列大小进行分组并确保结果正确。
data = [['Frankincense','5ml','1562'],
['Frankincense','10ml','1563'],
['Frankincense','15ml','1564'],
['Geranium','5ml','1565'],
['Geranium','10ml','1566'],
['Geranium','15ml','1567'],
['Ginger','5ml','1568'],
['Ginger','10ml','1569'],
['Ginger','15ml','1570'],
['Grapefruit','5ml','1571'],
['Grapefruit','10ml','1572'],
['Grapefruit','15ml','1573'],
['Lavender','5ml','1574'],
['Lavender','10ml','1575'],
['Lavender','15ml','1576']]
data.sort()
var title = data.reduce(function(result, value) {
if ( result.indexOf(value[1]) === -1 ) {
result.push(value[1]);
}
return result;
}, []).map(function(group) {
return group
});
var result = data.reduce(function(result, value) {
if ( result.indexOf(value[0]) === -1 ) {
result.push(value[0]);
}
return result;
}, []).map(function(group) {
return [group,...data.filter(function(_el) {
return _el[0] === group;
}).map(function(_el) { return _el[2]; })]
});
title.unshift('Name/Size')
result.unshift(title)
result.forEach(item => console.log(item.join('\t| ')))