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 in array - JavaScript
We are required to write a JavaScript function that takes in an array of positive as well as negative Numbers and changes the positive numbers to corresponding negative numbers and the negative numbers to corresponding positive numbers in place.
Let's write the code for this function ?
Example
Following is the code ?
const arr = [12, 5, 3, -1, 54, -43, -2, 34, -1, 4, -4];
const changeSign = arr => {
arr.forEach((el, ind) => {
arr[ind] *= -1;
});
};
changeSign(arr);
console.log(arr);
Output
Following is the output in the console ?
[
-12, -5, -3, 1, -54,
43, 2, -34, 1, -4,
4
]
Alternative Approach Using map()
You can also create a new array with inverted signs instead of modifying the original array:
const originalArray = [12, 5, 3, -1, 54, -43, -2, 34, -1, 4, -4];
const invertedArray = originalArray.map(num => num * -1);
console.log("Original:", originalArray);
console.log("Inverted:", invertedArray);
Original: [
12, 5, 3, -1, 54,
-43, -2, 34, -1, 4,
-4
]
Inverted: [
-12, -5, -3, 1, -54,
43, 2, -34, 1, -4,
4
]
How It Works
Both methods multiply each array element by -1, which effectively inverts the sign:
- Positive numbers become negative (e.g., 12 becomes -12)
- Negative numbers become positive (e.g., -43 becomes 43)
Comparison
| Method | Modifies Original? | Returns New Array? | Use Case |
|---|---|---|---|
forEach() |
Yes | No | In-place modification |
map() |
No | Yes | Preserve original data |
Conclusion
Use forEach() for in-place sign inversion or map() when you need to preserve the original array. Both methods efficiently multiply each element by -1 to invert signs.
Advertisements
