How to insert an element into all positions in an array using recursion - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ] ]
raja
Published on 01-Oct-2020 10:11:02
Advertisements