惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
3 Ways to Merge Arrays in JavaScript
Dmitri Pavlutin · 2021-04-06 · via Dmitri Pavlutin Blog

An array is a data structure representing an ordered collection of indexed items.

A common operation performed on multiple arrays is merge — when 2 or more arrays are merged to form a bigger array containing all the items of the merged arrays.

For example, having two arrays [1, 2] and [5, 6], then merging these arrays results in [1, 2, 5, 6].

In this post, you'll find 3 ways to merge arrays in JavaScript: 2 immutable (a new array is created after the merge) and 1 mutable (items are merged into an array).

Table of Contents

  • 1. Merge using the spread operator
  • 2. Merge using array.concat()
  • 3. Merge using array.push()
  • 4. Conclusion

1. Merge using the spread operator

If you want to know one good way to merge arrays in JavaScript, then remember the merge using the spread operator.

Write inside the array literal two or more arrays prefixed with the spread operator ..., and JavaScript will create a new array with all these arrays merged:


// merge array1 and array2

const mergeResult = [...array1, ...array2];


For example, let's merge 2 arrays heroes and villains:


const heroes = ['Batman', 'Superman'];

const villains = ['Joker', 'Bane'];

const all = [...heroes, ...villains];

console.log(all); // ['Batman', 'Superman', 'Joker', 'Bane']


Open the demo.

const all = [...heroes, ...villains] creates a new array having heroes and villains arrays merged.

The order of merged arrays inside the array literal does matter: items of the merged arrays are inserted in the same order as the arrays appear inside the literal.

For example, let's put the list of villains before the list of heroes in the merged array:


const heroes = ['Batman', 'Superman'];

const villains = ['Joker', 'Bane'];

const all = [...villains, ...heroes];

console.log(all); // ['Joker', 'Bane', 'Batman', 'Superman']


Open the demo.

The spread operator approach lets you merge 2 and even more arrays at once:


const mergeResult = [...array1, ...array2, ...array3, ...arrayN];


2. Merge using array.concat()

If you prefer a functional way to merge arrays, then you can use the array1.concat(array2) method:


// merge array1 and array2

const mergeResult = array1.concat(array2);


or using another form:


// merge array1 and array2

const mergeResult = [].concat(array1, array2);


array.concat() method doesn't mutate the array upon which it is called but returns a new array having the merge result.

Let's use array.concat() to merge the heroes and villains:


const heroes = ['Batman', 'Superman'];

const villains = ['Joker', 'Bane'];

const all1 = heroes.concat(villains);

const all2 = [].concat(heroes, villains);

console.log(all1); // ['Batman', 'Superman', 'Joker', 'Bane']

console.log(all2); // ['Batman', 'Superman', 'Joker', 'Bane']


Open the demo.

heroes.concat(villains) or [].concat(heroes, villains) return a new array where heroes and villains arrays are merged.

The concat method accepts multiple arrays as arguments, thus you can merge 2 or more arrays at once:


const mergeResult = [].concat(array1, array2, array3, arrayN);


3. Merge using array.push()

The merge performed using the spread operator or array.concat() creates a new array. However, sometimes you don't want to create a new array, but rather merge it into some existing array.

The approach below performs a mutable way to merge.

You might know already that array.push(item) method pushes an item to the end of the array, mutating the array upon which the method is called:


const heroes = ['Batman'];

heroes.push('Superman');

console.log(heroes); // ['Batman', 'Superman']


Open the demo.

array.push(item1, item2, ..., itemN) also accepts multiple items to push at once, thus you can push an entire array using the spread operator applied to arguments (in other words, performing a merge into):


// merge array2 into array1

array1.push(...array2);


For example, let's merge villains into heroes arrays:


const heroes = ['Batman', 'Superman'];

const villains = ['Joker', 'Bane'];

heroes.push(...villains);

console.log(heroes); // ['Batman', 'Superman', 'Joker', 'Bane']


Open the demo.

heroes.push(...villains) pushes all the items of villains array at the end of heroes array — performing a mutable merge. heroes array is mutated.

Side challenge: what expression would you use to push multiple arrays at once? Share your solution in a comment below!

4. Conclusion

JavaScript offers multiple ways to merge arrays.

You can use either the spread operator [...array1, ...array2], or a functional way [].concat(array1, array2) to merge 2 or more arrays. These approaches are immutable because the merge result is stored in a new array.

To perform a mutable merge, i.e. merge into an array without creating a new one, then you can use array1.push(...array2) approach.

What other ways to merge arrays do you know?