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
Inverting signs of integers in an array using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers (negatives and positives).
Our function should convert all positives to negatives and all negatives to positives and return the resulting array.
Method 1: Using for Loop
The traditional approach uses a for loop to iterate through each element and multiply by -1 to invert the sign:
const arr = [5, 67, -4, 3, -45, -23, 67, 0];
const invertSigns = (arr = []) => {
const res = [];
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(+el && el !== 0){
const inverted = el * -1;
res.push(inverted);
} else {
res.push(el);
}
}
return res;
};
console.log(invertSigns(arr));
[ -5, -67, 4, -3, 45, 23, -67, 0 ]
Method 2: Using map() Method
A more concise approach using the array map() method:
const arr = [5, 67, -4, 3, -45, -23, 67, 0];
const invertSigns = (arr = []) => {
return arr.map(num => num === 0 ? 0 : -num);
};
console.log(invertSigns(arr));
[ -5, -67, 4, -3, 45, 23, -67, 0 ]
Method 3: Simplified Approach
Since multiplying by -1 handles zero correctly (returns -0 which equals 0), we can simplify further:
const arr = [5, 67, -4, 3, -45, -23, 67, 0];
const invertSigns = (arr = []) => {
return arr.map(num => -num);
};
console.log(invertSigns(arr));
[ -5, -67, 4, -3, 45, 23, -67, 0 ]
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| For Loop | Long | Medium | Fast |
| map() with check | Medium | Good | Medium |
| Simple map() | Short | Excellent | Medium |
Conclusion
The simplest approach using arr.map(num => -num) is the most readable and concise. All methods produce the same result, with positive numbers becoming negative and vice versa.
Advertisements
