Home > Software design >  How to extract array of arrays values and push in same array in ES6?
How to extract array of arrays values and push in same array in ES6?

Time:09-21

I have this array of array

a1 = [['one', 'two', ['three', 'four']], ['five', 'six', ['seven', 'eight']]];

how to get this 'three' and 'four', 'seven' and 'eight' out of child array and push it in parent array as string like below

a2 = [['one', 'two', 'three, four'], ['five', 'six', 'seven, eight']];

like this. can I solve it with ES6?

Note: with space between 'three' 'four' and 'seven' 'eight' as shown in a2.

CodePudding user response:

Sounds like you want to join the inner arrays, yeah?

let a1 = [['one', 'two', ['three', 'four']], ['five', 'six', ['seven', 'eight']]];
let merged = a1.map((values) => {
  return values.map((value) => {
    return Array.isArray(value) ? value.join(', ') : value;
  });
});
console.log(merged)

CodePudding user response:

A double map will do the logic.

I used Array.isArray method to check whether the node is array or not.

a1 = [['one', 'two', ['three', 'four']], ['five', 'six', ['seven', ['eight']]]];
a2 = a1.map(node => node.map(item => Array.isArray(item) ? item.join(',') : item));
console.log(a2);

CodePudding user response:

I hope this is what you need:

var a1 = [
  ['one', 'two', ['three', 'four']],
  ['five', 'six', ['seven', ['eight']]]
];

a1.map(val => {
  return val.map((elem, index) => {
    val[index] = checkElemType(elem)
    return elem
  })

})


console.log(a1)

function checkElemType(elem) {
  if (Array.isArray(elem)) {
    elem.map((obj, index) => {
      elem[index] = checkElemType(obj)
      return obj
    })
    return elem.join(",")
  }


  return elem;
}

  • Related