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
-
Economics & Finance
Selected Reading
Insert value in the middle of every value inside array JavaScript
In JavaScript, you can insert operation objects between array elements to create alternating patterns. This technique is useful for building mathematical expressions or form builders.
Problem Statement
We have an array of numbers like this:
const numbers = [1, 6, 7, 8, 3, 98];
console.log("Original array:", numbers);
Original array: [ 1, 6, 7, 8, 3, 98 ]
We need to transform this array into objects with "value" keys, and insert operation objects between them using +, -, *, / alternately.
Expected Output Structure
The final result should look like this:
[
{ "value": 1 }, { "operation": "+" }, { "value": 6 }, { "operation": "-" },
{ "value": 7 }, { "operation": "*" }, { "value": 8 }, { "operation": "/" },
{ "value": 3 }, { "operation": "+" }, { "value": 98 }
]
Solution Using Array.reduce()
const numbers = [1, 6, 7, 8, 3, 98, 3, 54, 32];
const insertOperation = (arr) => {
const legend = '+-*/';
return arr.reduce((acc, val, ind, array) => {
// Add the current value as an object
acc.push({
"value": val
});
// Add operation object if not the last element
if (ind < array.length - 1) {
acc.push({
"operation": legend[ind % 4]
});
}
return acc;
}, []);
};
console.log(insertOperation(numbers));
[
{ 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 }
]
How It Works
The solution uses Array.reduce() to build a new array:
- legend[ind % 4]: Uses modulo operator to cycle through +, -, *, / operations
- ind : Prevents adding operation after the last element
- acc.push(): Adds value and operation objects to the accumulator array
Alternative Approach Using flatMap()
const numbers = [1, 6, 7, 8, 3];
const insertOperationFlatMap = (arr) => {
const operations = ['+', '-', '*', '/'];
return arr.flatMap((val, ind) => {
const valueObj = { "value": val };
if (ind === arr.length - 1) {
return [valueObj]; // Last element, no operation
}
const operationObj = { "operation": operations[ind % 4] };
return [valueObj, operationObj];
});
};
console.log(insertOperationFlatMap(numbers));
[
{ value: 1 }, { operation: '+' },
{ value: 6 }, { operation: '-' },
{ value: 7 }, { operation: '*' },
{ value: 8 }, { operation: '/' },
{ value: 3 }
]
Conclusion
Both reduce() and flatMap() can insert alternating operations between array elements. The reduce() approach is more explicit, while flatMap() provides a cleaner functional style.
Advertisements
