JavaScript: How to join / combine two arrays to concatenate into one array?

JavascriptArrays

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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'

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDiesal11View Question on Stackoverflow
Solution 1 - JavascriptMoin ZamanView Answer on Stackoverflow
Solution 2 - Javascriptvitaly-tView Answer on Stackoverflow
Solution 3 - JavascriptGollyJerView Answer on Stackoverflow