Inverting signs in array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
raja
Updated on 14-Sep-2020 14:03:41

Advertisements