0

I want to make an array flat.

// example of the start array
const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

However I'd like it to be:

// end result
[
  { foo: "bar", baz: "qux"},
  { quux: "corge", grault: "garply" },
  { waldo: "fred", plugh: "xyzzy" },
  { thud: "barbra", streisand: "woohoo" }
]

Now the following example gives the result: (2) [Array(2), Array(2)].

const myArray = [
  [ 
   { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
   { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

let newArray = [];
myArray.forEach((subArray) => newArray.push(subArray));
console.log(newArray);
Remi
  • 4,663
  • 11
  • 49
  • 84

4 Answers4

5

You can flatten the arrays using Array.flat():

const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

const newArray = myArray.flat();

console.log(newArray);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You can use spread operator to get what you want (but this is a quick fix, there are better ways to do it):

const myArray = [
  [ 
   { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
   { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

let newArray = [];
myArray.forEach((subArray) => newArray.push(subArray));
newArray = [...newArray[0], ...newArray[1]];
console.log(newArray);
Darwin Gonzalez
  • 175
  • 1
  • 9
1

You can use concat to merge arrays:

const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

const merged = [].concat.apply([], myArray);
console.log(merged);
Diogo Peres
  • 1,302
  • 1
  • 11
  • 20
0

You can use Array.concat():

const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

let newArray = [];
myArray.forEach(
    (subArray) => {
        newArray = newArray.concat(subArray);
    }
);
console.log(newArray);
Elias Soares
  • 9,884
  • 4
  • 29
  • 59