- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to insert an element into all positions in an array using recursion - JavaScript?
We are required to declare a function, let’s say insertAllPositions, which takes two arguments −
an element, x, and an array, arr. Functions must return an array of arrays, with each array corresponding to arr with x inserted in a possible position.
That is, if arr is the length N, then the result is an array with N + 1 arrays −
For example, the result of insertAllPositions(10, [1,2,3]) should be −
const output = [ [10,1,2,3], [1,10,2,3], [1,2,10,3], [1,2,3,10] ];
We are required to write this function purely using recursion.
Example
Following is the code −
const arr = [1, 2, 3]; const num = 10; const insertAllPositions = (num, arr) => { return arr.length ? [[num, ...arr]] .concat(insertAllPositions(num, arr.slice(1)) .map(el => { return [arr[0]].concat(el); })) : [[num]] }; console.log(insertAllPositions(num, arr));
Output
This will produce the following output on console −
[ [ 10, 1, 2, 3 ], [ 1, 10, 2, 3 ], [ 1, 2, 10, 3 ], [ 1, 2, 3, 10 ] ]
- Related Articles
- How to insert an element into DOM using jQuery?
- Find the middle element of an array using recursion JavaScript
- Finding all peaks and their positions in an array in JavaScript
- C Program to insert an array element using pointers.
- Finding product of an array using recursion in JavaScript
- Adding an element in an array using Javascript
- Using recursion to remove consecutive duplicate entries from an array in JavaScript
- Using recursion to remove consecutive duplicate entries from an array - JavaScript
- Python program to insert an element into sorted list
- How to push an element into array in MongoDB?
- How to convert an object into an array in JavaScript?
- How to insert an item into a C# list by using an index?
- Insert an element to List using ListIterator in Java
- Swift Program to Insert an Element in an Array at a Specified Index
- Insert an element into Collection at specified index in C#

Advertisements