JavaScript - 基于 3 个数组形成数组的函数(合并)

给定以下 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€']

]

如何使函数传递两个变量:grams 和 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€'],

]


慕码人8056858
浏览 189回答 1
1回答

翻阅古今

这是一个解决方案,它获取一个组的价格,如果给定或所有组,然后将这些组分配给单个数组。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; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript