-3

How can I convert this complex array:

[
  [
    { nums: [2,2] },
    { nums: [2,3] },
    { nums: [2,6] }

  ],
  [
    { nums: [3,2] },
    { nums: [3,4] },
    { nums: [3,5] },
    { nums: [3,9] }

  ],
  [  
    { nums: [4,2] },
    { nums: [4,3] },
  ]
]

Into this simplified version?:

  [
    [2,2],
    [2,3],
    [2,6],
    [3,2],
    [3,4],
    [3,5],
    [3,9],
    [4,2],
    [4,3]
  ]
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98

3 Answers3

1

You can use .flat() to flatten the array and then .map() to map the objects to only their nums field like so:

let data = [
  [
    { nums: [2,2] },
    { nums: [2,3] },
    { nums: [2,6] }

  ],
  [
    { nums: [3,2] },
    { nums: [3,4] },
    { nums: [3,5] },
    { nums: [3,9] }

  ],
  [  
    { nums: [4,2] },
    { nums: [4,3] },
  ]
];

console.log(data.flat().map(obj => obj.nums));
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
1

You can convert them using the following line of codes:

let finalArray =[];
array.forEach((element)=>{
element.forEach((innerElement)=>{
    finalArray.push(innerElement.nums)
   }  
})
Minal Shah
  • 1,402
  • 1
  • 5
  • 13
1

You can make use of flatMap to flatten the data:

var array=[
  [
    { nums: [2,2] },
    { nums: [2,3] },
    { nums: [2,6] }

  ],
  [
    { nums: [3,2] },
    { nums: [3,4] },
    { nums: [3,5] },
    { nums: [3,9] }

  ],
  [  
    { nums: [4,2] },
    { nums: [4,3] },
  ]
];

var result = array.flatMap(e=>e.map(p=>p.nums));

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19