开发者

JavaScript: 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 开发者_StackOverflow中文版is read the 4th element in the array would return "d"

How would i do this?


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'


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.


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(`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜