192

I'm trying to combine 2 arrays in javascript into one.

var lines = new Array("a","b","c");
lines = new Array("d","e","f");

This is a quick example, i want to be able to combine them so that when the second line is read the 4th element in the array would return "d"

How would i do this?

Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
Diesal11
  • 3,389
  • 9
  • 28
  • 29
  • 3
    Same question, more (detailed) answers: http://stackoverflow.com/questions/1584370/ – ignis Aug 18 '12 at 06:44
  • 3
    @David All simple questions have more answers, because more people google them (or ::shivers:: use the site's built-in search feature). – Camilo Martin Dec 14 '12 at 06:58
  • 13
    @ignis This is not a duplicate. That question is specifically asking about removing duplicates in the resulting array. It is more specific, and this question is much more general. – J.D. Aug 22 '15 at 16:08

3 Answers3

310
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
  • 4
    @Matt yes because its just an array it doesn't track its contents. – Nate-Wilkins Apr 05 '13 at 19:19
  • 1
    Is there a way to concatenate an array of arrays - i.e. for [[1,2],[3,4],[5,6],..] to become [1,2,3,4,5,6,..]? – geotheory Nov 07 '13 at 23:24
  • 3
    @geotheory check underscorejs there is a reduce fonction for that underscorejs.org ;) – picsoung Nov 28 '13 at 00:05
  • 31
    old post, but for anyone googling now, @geotheory's question has a simple answer: `Array.prototype.concat.apply([], [[1,2],[3,4],[5,6]])` – sjmeverett Nov 03 '14 at 10:29
  • 34
    with **es6** : `c=a.push(...b)` – Abdennour TOUMI Aug 14 '16 at 08:02
  • 13
    You can also do: const newArr = [...arr1, ...arr2]; – Diego Fortes Feb 18 '18 at 20:30
  • 1
    For anyone wanting to use the syntax `c=a.push(...b)`, if you need to check its [compatibility with different browsers](https://caniuse.com/#search=javascript%20spread) or if you want more information on `...`, it's called the spread operator or, more generally, [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). – Dave F Apr 12 '20 at 15:14
  • I imagine the actual answer is the fastest method? – JFFIGK Nov 21 '20 at 09:27
  • 1
    @geotheory [`[[1,2],[3,4],[5,6]].flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat). – Sebastian Simon Dec 06 '20 at 18:40
  • @JFFIGK No, quite the opposite, it is the slowest method. The fastest is via spread operator - see my answer. – vitaly-t Aug 25 '21 at 10:49
20

Using modern JavaScript syntax - spread operator:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];

const c = [...a, ...b]; // c = ['a', 'b', 'c', 'd', 'e', 'f']

It is also the fastest way to concatenate arrays in JavaScript today.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
3

Speed test using local nodejs v16.4.
Object Spread is 3x faster.

ObjectCombining.js

export const ObjectCombining1 = (existingArray, arrayToAdd) => {
  const newArray = existingArray.concat(arrayToAdd);
  return newArray;
};

export const ObjectCombining2 = (existingArray, arrayToAdd) => {
  const newArray = [ ...existingArray, ...arrayToAdd ]
  return newArray
};

ObjectCombining.SpeedTest.js

import Benchmark from 'benchmark';

import * as methods from './ObjectCombining.js';

let suite = new Benchmark.Suite();

const existingArray = ['a', 'b', 'c'];
const arrayToAdd = ['d', 'e', 'f'];

Object.entries(methods).forEach(([name, method]) => {
  suite = suite.add(name, () => method(existingArray, arrayToAdd));

  console.log(name, '\n', method(existingArray, arrayToAdd),'\n');
});

suite
  .on('cycle', (event) => {
    console.log(`  ${event.target}`);
  })
  .on('complete', function () {
    console.log(`\n ${this.filter('fastest').map('name')} is fastest.\n`);
  })
  .run({ async: false });

Result results

GollyJer
  • 23,857
  • 16
  • 106
  • 174
  • Can you add `existingArray.push(...arrayToAdd)` test, please? – vitaly-t Feb 20 '23 at 17:38
  • @vitaly-t or, [given that](https://ericlippert.com/2012/12/17/performance-rant/) the benchmark is [rather useless](https://mrale.ph/blog/2012/12/15/microbenchmarks-fairy-tale.html) - don't. – VLAZ Feb 20 '23 at 17:46