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
  • 2,517
  • 3
  • 26
  • 43

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
  • 145,770
  • 24
  • 170
  • 162
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
  • 167
  • 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,195
  • 1
  • 8
  • 19
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
  • 7,626
  • 4
  • 22
  • 48