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
Constructing an array of addition/subtractions relative to first array element in JavaScript
We are required to write a JavaScript function that takes in an array of positive integers. Our function should map this array to an array of string integers.
The array should contain the number we should add/subtract to the first element to achieve the corresponding element.
Problem
For example, if we have:
[4, 3, 6, 2]
We need to calculate the difference between each element and the first element (4):
- 4 - 4 = 0 ? "+0"
- 3 - 4 = -1 ? "-1"
- 6 - 4 = 2 ? "+2"
- 2 - 4 = -2 ? "-2"
The result should be:
['+0', '-1', '+2', '-2']
Solution
const arr = [4, 3, 6, 2];
const buildRelative = (arr = []) => {
const res = [];
const firstElement = arr[0];
for (let i = 0; i < arr.length; i++) {
const difference = arr[i] - firstElement;
if (difference >= 0) {
res.push('+' + difference);
} else {
res.push('' + difference);
}
}
return res;
};
console.log(buildRelative(arr));
['+0', '-1', '+2', '-2']
Alternative Solution Using map()
We can make the code more concise using the map() method:
const arr = [4, 3, 6, 2];
const buildRelative = (arr = []) => {
const firstElement = arr[0];
return arr.map(num => {
const difference = num - firstElement;
return difference >= 0 ? '+' + difference : '' + difference;
});
};
console.log(buildRelative(arr));
['+0', '-1', '+2', '-2']
How It Works
The function works by:
- Storing the first element as our reference point
- Iterating through each element in the array
- Calculating the difference between each element and the first element
- Adding a "+" prefix for non-negative differences
- Negative differences automatically include the "-" sign
Conclusion
This approach efficiently transforms an array into relative differences from its first element. The map() method provides a cleaner, more functional programming approach.
Advertisements
