Home > Software design >  How to join javascript array elements without forloop
How to join javascript array elements without forloop

Time:12-08

I have from a mongoose query result:

{
    "store": [
        {
            "items": [
                "A1",
                "A2"
            ]
        },
        {
            "items": [
                "A3",
                "A4"
            ]
        },
        {
            "items": [
                "B1",
                "B2"
            ]
        },
        {
            "items": [
                "B3",
                "B4"
            ]
        },
        {
            "items": [
                "C8",
                "C9",
                "C10"
            ]
        }
    ]
}

I need this: ["A1","A2","A3","A4","B1","B2","B3","B4","C8","C9",C10] Is there any way to do this without using foreach loop, as my array will be so long and it will be time consuming.

CodePudding user response:

let data = {
  'store': [
    {
      'items': [
        'A1',
        'A2'
      ]
    },
    {
      'items': [
        'A3',
        'A4'
      ]
    },
    {
      'items': [
        'B1',
        'B2'
      ]
    },
    {
      'items': [
        'B3',
        'B4'
      ]
    },
    {
      'items': [
        'C8',
        'C9',
        'C10'
      ]
    }
  ]
}

let result = data['store'].flatMap(value => value.items)

console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

To boost the performance even more you can directly use an aggregation to make use of the faster C performing in the database:

I am assuming your database document looks something like this: enter image description here

If you use an aggregation like this:

let result = Model.aggregate([
  {'$match':{'_id': "YourDesiredId"}}, // Add this line in case you want to match a specific document
  {
    '$unwind': {
      'path': '$store'
    }
  }, {
    '$unwind': {
      'path': '$store.items'
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'items': {
        '$push': '$store.items'
      }
    }
  }, {
    '$project': {
      '_id': 0
    }
  }
])

Your output will be:

items:["A1","A2","A3","A4","B1","B2","B3","B4","C8","C9","C10"]
  • Related