Insert value in the middle of every value inside array JavaScript


We have an array of numbers like this −

const numbers = [1, 6, 7, 8, 3, 98];

We have to convert this array of numbers into an array of objects with each object having a key as “value” and its value as a specific value of the array element. Besides this we have to insert object between two pre-existing elements with key as “operation” and using alternatively one of +, - * , / as its value.

Therefore, for the numbers array, the output would look something like this −

[
   { "value": 1 }, { "operation": "+" }, { "value": 6 }, { "operation": "-"},
   { "value": 7 }, { "operation": "*" }, { "value": 8 }, { "operation":"/" },
   { "value": 3 }, { "operation": "+" }, {"value": 98}
]

Therefore, let’s write the code for this function −

Example

const numbers = [1, 6, 7, 8, 3, 98, 3, 54, 32];
const insertOperation = (arr) => {
   const legend = '+-*/';
   return arr.reduce((acc, val, ind, array) => {
      acc.push({
         "value": val
      });
      if(ind < array.length-1){
         acc.push({
            "operation": legend[ind % 4]
         });
      };
      return acc;
   }, []);
};
console.log(insertOperation(numbers));

Output

The output in the console will be −

[
   { value: 1 }, { operation: '+' },
   { value: 6 }, { operation: '-' },
   { value: 7 }, { operation: '*' },
   { value: 8 }, { operation: '/' },
   { value: 3 }, { operation: '+' },
   { value: 98 }, { operation: '-' },
   { value: 3 }, { operation: '*' },
   { value: 54 }, { operation: '/' },
   { value: 32 }
]

Updated on: 24-Aug-2020

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements