【问题标题】:Concat a variable number of array连接可变数量的数组
【发布时间】:2022-08-17 15:58:29
【问题描述】:

语境: 在我的网店网站上,在产品列表页面上,客户可以选择一个或多个关键字(标签)来过滤产品。

所有产品都在一个数组中(产品) 和选定的关键字在标签.

// tags filter
var listProduct = []
for(var i = 0; i < tags.length; i++){
  listProduct[i] = products.filter(e => {
     if(e.tags){
        return (e.tags.includes(tags[i].toLowerCase())) ? true : false
     }else{
        return false
     }
  });
}


我现在有几个数组(listProduct),我知道我有标签长度其中。 我必须使用 concat() 函数来连接所有这些数组,但我不知道该怎么做......

products = listProduct[0].concat(listProduct[1], listProduct[2] .... listProduct[?])

非常感谢! 文森特

  • 仅供参考:includes 已经返回一个布尔值,所以? true : false 是多余的。
  • 您可以使用flat 来展平listProduct 数组。

标签: javascript arrays


【解决方案1】:

希望这对你有用。

const products = listProduct.reduce((p, c) => p.concat(c));

【讨论】:

    【解决方案2】:

    我假设以下是您拥有的数据:

    const  tags = [
        'cloth','electronic','document','entertainment'
      ];
    
    const products  =  [
        {
        productName: "TV",
        tags: ['electronic','entertainment'
          ]
        },
        {
          productName: "Phone",
          tags: [
            'electronic'
          ]
        },
        {
          productName: "Book",
          tags: [
            'document'
          ]
        },
        {
          productName: "Shirt",
          tags: [
            'cloth'
          ]
        },
        {
          productName: "Washing Machine",
          tags: [
            'electronic'
          ]
        },
        {
          productName: "EBook",
          tags: [
            'NA'
          ]
        }
      ]
    }

    现在你想通过标签过滤它并将结果连接到一个数组中?

    const  tags = [
        'cloth','document','entertainment'
      ];
    
    const products  =  [
        {
        productName: "TV",
        tags: ['electronic','entertainment'
          ]
        },
        {
          productName: "Phone",
          tags: [
            'electronic'
          ]
        },
        {
          productName: "Book",
          tags: [
            'document'
          ]
        },
        {
          productName: "Shirt",
          tags: [
            'cloth'
          ]
        },
        {
          productName: "Washing Machine",
          tags: [
            'electronic'
          ]
        },
        {
          productName: "EBook",
          tags: [
            'NA'
          ]
        }
      ]
      
      const finalArray = products.filter(product => { 
        return tags.find(tag =>  product.tags.includes(tag))
      })
      
      
      console.log("finalArray", finalArray)
      
      
      

    所以通过这种方式你会得到使用 ES6 的结果

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 2014-04-19
      • 2012-09-05
      相关资源
      最近更新 更多