
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge two arrays with alternating Values in JavaScript
Let’s say, we are required to write a function that takes in two arrays and returns a new array that contains values in alternating order from first and second array. Here, we will just loop over both the arrays simultaneously picking values from them one after the other and feed them into the new array.
The full code for doing the same will be −
Example
const arr1 = [34, 21, 2, 56, 17]; const arr2 = [12, 86, 1, 54, 28]; let run = 0, first = 0, second = 0; const newArr = []; while(run < arr1.length + arr2.length){ if(first > second){ newArr[run] = arr2[second]; second++; }else{ newArr[run] = arr1[first]; first++; } run++; }; console.log(newArr);
Output
The console output for this code will be −
[ 34, 12, 21, 86, 2, 1, 56, 54, 17, 28 ]
- Related Questions & Answers
- How to merge two arrays in JavaScript?
- How to merge two arrays with objects in one in JavaScript?
- JavaScript - Merge two arrays according to id property
- Program to merge two strings in alternating fashion in Python
- Merge two sorted arrays in C#
- Merge two sorted arrays in Java
- Merge two objects in JavaScript ignoring undefined values
- Merge two sorted arrays using C++.
- How to merge an array with an object where values are arrays - JavaScript
- Comparing corresponding values of two arrays in JavaScript
- Merge two arrays using C# AddRange() method
- Merge two sorted arrays in Python using heapq?
- Merge two arrays keeping original keys in PHP
- JavaScript merge multiple Boolean arrays with the OR || operator
- Merge two sorted arrays to form a resultant sorted array in JavaScript
Advertisements