
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 ]
Advertisements