给定以下js数组:
var prices_A =[
['company','100g','200g','300g'],
['business_a','40€','50€',''],
['business_b','50€','61€','42€'],
['business_c','66€','','31€']
]
var prices_B =[
['company','100g','200g','300g'],
['business_b','40€','50€',''],
['business_d','50€','61€','42€'],
['business_e','66€','','31€']
]
var prices_C =[
['company','100g','200g','300g'],
['business_e','40€','50€',''],
['business_b','66€','','31€']
]如何使函数传递两个变量:gram和price_type,返回基于输入的数组合并(变量传递)。price_type可以是: prices_A、prices_B、prices_C或prices_all。当引入prices_all时,它应该查询合并所有价格(prices_A、prices_B和prices_C)
示例1:
var prices = myfunction(200,prices_C){}结果:
prices =[
['company','200g'],
['business_e','50€']
]示例2:
var prices = myfunction(100,prices_all){}结果:
prices =[
['company','100g_A','100g_B','100g_C'],
['business_a','40€',''],
['business_b','50€','40€','66€'],
['business_c','66€',''],
['business_d','','50€',''],
['business_e','','66€','40€'],
]发布于 2019-06-19 09:41:39
这是一个解决方案,它为一个组(如果给定)或所有组获得一个价格,然后它将这些组分配给一个数组。
function getPrices(weight, category) {
function getByGroup(group) {
var index = group[0].indexOf(weight);
return group
.map(a => [0, index].map(i => a[i]))
.filter(a => a[1]);
}
return category in allPrices
? getByGroup(allPrices[category])
: Object.entries(allPrices).reduce((r, [k, group], i) => {
var temp = getByGroup(group),
index;
if (!temp.length) return r;
temp[0][1] += '_' + k.slice(-1);
if (!r) return temp;
index = r[0].push(temp[0][1]) - 1;
temp.forEach(([company, price]) => {
var row = r.find(([c]) => c === company);
if (!row) {
r.push(row = [company]);
}
row[index] = price;
});
r.forEach(a => a[index] = a[index] || '');
return r;
}, undefined);
}
var prices_A = [['company', '100g', '200g', '300g'], ['business_a', '40€', '50€', ''], ['business_b', '50€', '61€', '42€'], ['business_c', '66€', '', '31€']],
prices_B = [['company', '100g', '200g', '300g'], ['business_b', '40€', '50€', ''], ['business_d', '50€', '61€', '42€'], ['business_e', '66€', '', '31€']],
prices_C = [['company', '100g', '200g', '300g'], ['business_e', '40€', '50€', ''], ['business_b', '66€', '', '31€']],
allPrices = { prices_A, prices_B, prices_C };
console.log(getPrices('200g', 'prices_C'));
console.log(getPrices('100g', 'prices_all'));.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/56663687
复制相似问题