Home > Back-end >  Concat a variable number of array
Concat a variable number of array

Time:08-17

Context: On my e-shop website, on a product listing page, a customer can select one or several keywords (tags) to filter products.

All products are in a array (products) and the selected keywords are in tags.

// 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
     }
  });
}


I now have several arrays (listProduct), I know I have tags.length of them. I have to use the concat() function to concat all theses arrays, but i don't know how to do...

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

Thanks a lot! Vincent

CodePudding user response:

hope this works for you. there are 2 ways:

first, you can use reduce method to concat the array:

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

second, you can use flat method to flatten the original array to make it one leveled array:

const products = listProduct.flat();

CodePudding user response:

I assume that below are the data you have:

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'
      ]
    }
  ]
}

Now you want to filter it by tags and concat the results into an array?

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)
  
  
  

So in this way you will get the result using ES6

  • Related