Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 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
