0

I have an array

  var input = [["group1","group2","group3" ], ["group1", "group5" ]]

I would like to merge two objects like this :

  ["group1","group2","group3", "group1", "group5" ]

I tried to merge two objects in one array, however, I couldn't get the answer. Any help would be appreciated.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Jane
  • 139
  • 1
  • 1
  • 10
  • 1
    No, you don't: you want to concatenate arrays, not merge objects. To concatenate arrays, there is the built in [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) function. – Mike 'Pomax' Kamermans Jan 14 '19 at 21:06
  • This is called "flattening". –  Jan 14 '19 at 21:07

6 Answers6

4

I'm not too familiar with js, but can't you concat two arrays with something like

var merged = input[0].concat(input[1]);
Chris
  • 2,254
  • 8
  • 22
2

You can use concat() like so:

const input = [
  ["group1", "group2", "group3"],
  ["group1", "group5"]
];

const output = [].concat.apply([], input);

console.log(output);

Or alternatively, Array.prototype.flat():

const input = [
  ["group1", "group2", "group3"],
  ["group1", "group5"]
];

const output = input.flat(1);

console.log(output);

Or if that is "hard" data, and will not change, you could use an even simpler concat() operation:

const input = [
  ["group1", "group2", "group3"],
  ["group1", "group5"]
];

const output = input[0].concat(input[1]);

console.log(output);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You can use the concat function to combine the arrays.

const resultArr = [];

input.forEach(curr => {
  resultArr.concat(curr);
});
pengcheng95
  • 292
  • 4
  • 13
0

You're talking about 'flattening the array'...

const flatten = (array) => {
  return array.reduce((flat, toFlatten) => {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}
console.log(flatten([[1,2,[3]],4])); 
SakoBu
  • 3,972
  • 1
  • 16
  • 33
0

ES5

array.reduce(function(a, x) { return a.concat(x); }, []);

ES6

array.reduce((a, x) => a.concat(x), []);
Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44
0

There is multiple approaches that you could take, my favorite would be to use the reduce method to transform your bi-dimensional array into one flat array and it would look like this :

function reducer(final_flat_array, inputItem) {
    return [...final_flat_array, ...inputItem]
};
let flat_array = input.reduce(reducer, []);

or a more 'imperative' way I guess :

let flat_array = [];
input.forEach(item => flat_array.push(item);
MaieonBrix
  • 1,584
  • 2
  • 14
  • 25