Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How to join javascript array elements without forloop

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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"]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!