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

99
Views
Split array elements dynamically

I have below scenarios to handle.

let data = [
    [ "ALISHA", "SUICA", "PASMO" ],
    [ "HARMONY" ],
    [ "OCTOPUS" ]
]

let data1 = [
    [ "ALISHA",  ],
    [ "HARMONY" ],
    [ "OCTOPUS", "SUICA", "PASMO" ]
]

For both of the above data, i want the result to look like this.

let result = [
    [ "ALISHA" ],
    [ "HARMONY" ],
    [ "OCTOPUS" ], 
    [ "SUICA" ],
    [ "PASMO" ]
]

Can someone please let me know how to achieve this. I tried the following but no success

let result = []
for (let i = 0; i < data.length; i++) {
    let split = data[i].split(",");  // just split once
    result.push(split[0]); // before the comma 
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

we will use forEach method on main array inside forEach we will use if condition if is array and length more than 1 will add another forEach method and push sub array to main array after that remove sub array look like that

let data = [
  ["ALISHA"],
  ["HARMONY"],
  ["OCTOPUS", "SUICA", "PASMO"]
]

data.forEach((cur, index) => {
  if (Array.isArray(cur) && cur.length > 1) {
    cur.forEach(cur => data.push([cur]))
    data.splice(index, 1);
  }
})

console.log(data)

about 4 years ago · Juan Pablo Isaza Report

0

Uses Array.reduce extract all elements, then convert to [string] by Array.map.

const data = [
    [ "ALISHA" ],
    [ "HARMONY" ],
    [ "OCTOPUS", "SUICA", "PASMO" ]
]

console.log(
  data.reduce((pre, cur) => [...pre, ...cur], []).map(item => [item])
  // data.reduce((pre, cur) => pre.concat(...cur), []).map(item => [item]) // different methods but same logic (uses Array.concat instead of spread operator)
)

about 4 years ago · Juan Pablo Isaza Report

0

You can use flat and map

const data = [["ALISHA"], ["HARMONY"], ["OCTOPUS", "SUICA", "PASMO"]];

const result = data.flat().map((a) => [a]);
console.log(result);

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!