Diesal11
Diesal11

Reputation: 3417

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

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?

Upvotes: 194

Views: 238596

Answers (3)

vitaly-t
vitaly-t

Reputation: 25830

Using ES6 JavaScript - spread syntax:

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.


However, when dealing with large arrays, it is more efficient to chain them (concatenate logically):

function chainArrays<T>(...arr: T[][]): Iterable<T> {
    return {
        [Symbol.iterator](): Iterator<T> {
            let i = 0, k = -1, a: T[] = [];
            return {
                next(): IteratorResult<T> {
                    while (i === a.length) {
                        if (++k === arr.length) {
                            return {done: true, value: undefined};
                        }
                        a = arr[k];
                        i = 0;
                    }
                    return {value: a[i++], done: false};
                }
            };
        }
    }
}

// usage example:

const a = [1, 2];
const b = [3, 4];
const c = [5, 6];

for (const value of chainArrays(a, b, c)) {
    console.log(value); //=> 1, 2, 3, 4, 5, 6
}

Above, we have to use while(i === a.length) logic in order to skip all empty arrays, while also for jumping to the next array at the end of the current one.

A generator approach for the same is much simpler, while also slower:

function* chainArrays<T>(...arr: T[][]) {
    for (const i of arr)
        for (const v of i)
            yield v;
}

// test:

for (const value of chainArrays(a, b, c)) {
    console.log(value); //=> 1, 2, 3, 4, 5, 6
}

Internally, a generator is translated into a more verbose IterableIterator, which used to perform slower than a manual iterable, but JavaScript engines keep improving, so it's for you to test it out in your environment ;) But I tested it under Node v20, and on average the manual iterable performs 2 times faster than our generator here.

For a complete TypeScript implementation (including reversed logic), see this gist, or this repo.

Upvotes: 26

GollyJer
GollyJer

Reputation: 26662

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

Upvotes: 4

Moin Zaman
Moin Zaman

Reputation: 25435

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'

Upvotes: 310

Related Questions