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
Changing positivity/negativity of Numbers in a list in 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.
Example
The code for this will be ?
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
The output in the console ?
[
-12, -5, -3, 1, -54,
43, 2, -34, 1, -4,
4
]
Alternative Approach Using map()
Instead of modifying the original array, you can create a new array with sign changes:
const arr = [12, 5, 3, -1, 54, -43, -2, 34, -1, 4, -4];
const changeSignCopy = arr => {
return arr.map(num => num * -1);
};
const newArr = changeSignCopy(arr);
console.log("Original:", arr);
console.log("Sign changed:", newArr);
Original: [ 12, 5, 3, -1, 54, -43, -2, 34, -1, 4, -4 ]
Sign changed: [
-12, -5, -3, 1, -54,
43, 2, -34, 1, -4,
4
]
How It Works
Both approaches multiply each number by -1. The first method modifies the original array in place using forEach(), while the second creates a new array using map() without changing the original.
Conclusion
Use forEach() to modify arrays in place, or map() to create new arrays with sign changes. Both effectively flip the positivity/negativity of numbers by multiplying by -1.
