 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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 } ]Advertisements
 