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
Make array numbers negative JavaScript
In JavaScript, you can convert all positive numbers in an array to negative while keeping already negative numbers unchanged. This is useful for data transformations where you need to invert positive values.
Let's say we have the following array:
const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];
We need to write a function that converts all positive numbers to negative while leaving negative numbers unchanged (like 4 to -4, 6 to -6, but -12 stays -12).
Using Array.reduce()
const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];
const changeToNegative = (arr) => {
return arr.reduce((acc, val) => {
const negative = val < 0 ? val : val * -1;
return acc.concat(negative);
}, []);
};
console.log(changeToNegative(arr));
[ -7, -2, -3, -4, -5, -7, -8, -12, -12, -43, -6 ]
Using Array.map() (Simpler Approach)
const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];
const changeToNegative = (arr) => {
return arr.map(num => num < 0 ? num : -num);
};
console.log(changeToNegative(arr));
[ -7, -2, -3, -4, -5, -7, -8, -12, -12, -43, -6 ]
Using Math.abs() for Cleaner Code
const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];
const changeToNegative = (arr) => {
return arr.map(num => -Math.abs(num));
};
console.log(changeToNegative(arr));
[ -7, -2, -3, -4, -5, -7, -8, -12, -12, -43, -6 ]
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
reduce() |
Medium | Slower | Complex transformations |
map() with condition |
Good | Fast | Preserving negative values |
Math.abs() |
Excellent | Fast | Making all values negative |
Conclusion
Use Math.abs() with map() for the cleanest solution when making all numbers negative. The conditional map() approach is best when you need to preserve existing negative values unchanged.
Advertisements
