admin管理员组文章数量:1134247
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?
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?
Share Improve this question edited Oct 27, 2023 at 14:01 Heretic Monkey 12.1k7 gold badges60 silver badges130 bronze badges asked Oct 20, 2010 at 6:12 Diesal11Diesal11 3,4179 gold badges30 silver badges29 bronze badges 4- 3 Same question, more (detailed) answers: stackoverflow.com/questions/1584370 – ignis Commented Aug 18, 2012 at 6: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 Commented Dec 14, 2012 at 6: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. Commented Aug 22, 2015 at 16:08
- These days, it is important to distinguish, whether you really do need an array, or if an iterable will suffice, because the answer would be different. – vitaly-t Commented Sep 25, 2024 at 13:11
3 Answers
Reset to default 310var 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 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.
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(`
本文标签:
javascriptHow to joincombine two arrays to concatenate into one arrayStack Overflow
版权声明:本文标题:javascript - How to joincombine two arrays to concatenate into one array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:http://www.betaflare.com/web/1736803831a1953603.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论