Home > Net >  Split array elements dynamically
Split array elements dynamically

Time:09-17

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 
}

CodePudding user response:

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)
)

CodePudding user response:

You can use flat and map

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

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

CodePudding user response:

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)

  • Related