Javascript: How to Combine & Filter Arrays

有些话、适合烂在心里 提交于 2019-12-02 13:05:14

You can use the combination of map and filter to first combine the three arrays you have and then filter out arrays that match item_type='bundle'.

var item_type  = ['bundle', 'simple', 'simple'],
    item_name  = ['product1', 'product2', 'product3'],
    item_price = [1.99, 2.99, 3.99],
    res = item_type.map(function(v,i) {
        //combine arrays
        return [v, { [item_name[i]]: item_price[i] }]; 
    }).filter(function(o) {
        // only allow items where 'item_type' is not "bundle"
        return o[0] != "bundle";
    });

    console.log(JSON.stringify(res, 2, null));

Yes... JS is missing an Array.prototype.zip() functionality. Let's invent it and solve accordingly.

Array.prototype.zip = function(...a){
  return this.map((e,i) => [e].concat(a.map(sa => sa[i])));
};

var itemType  = ["bundle", "simple", "simple"],
    itemName  = ["product1", "product2", "product3"],
    itemPrice = [1.99,2.99,3.99],
    result    = itemType.zip(itemName,itemPrice)
                        .map(sa => [sa[0],{[sa[1]]:sa[2]}])
                        .filter(t => t[0] === "simple");
console.log(result);

PS: I have swapped the place of the last .map() and .filter() functions to fit your requirement but amending the question yielding changes in the previous answers are not encouraged in SO.

First, combine them all into an array of objects via map, then filter, then map again into the representation you need. Something like:

item_type
    .map((type, index) => ({ 
       type, 
       index, 
       name: item_name[index], 
       price: item_price[index]
    }))
    .filter(el => el.type === 'simple')
    .map(el => [el.type, {name: el.name, price: el.price}])

You could filter the columns, transpose the arrays and build the wanted inner arrays.

var item_type = ['bundle', 'simple', 'simple'],
    item_name = ['product1', 'product2', 'product3'],
    item_price = [1.99, 2.99, 3.99],
    result = [item_type, item_name, item_price]
        .map((a, _, aa) => a.filter((b, i) => aa[0][i] !== 'bundle'))
        .reduce((r, a, i) => (a.forEach((b, j) => (r[j] = r[j] || [], r[j][i] = b)), r), [])
        .map(a => ({ type: a[0], info: { name: a[1], price: a[2] } }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!