Inverting signs of integers in an array using JavaScript

JavascriptWeb DevelopmentFront End Technology

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.

Example

Following is the code −

 Live Demo

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));

Output

[ -5, -67, 4, -3, 45, 23, -67, 0 ]
raja
Published on 17-Apr-2021 13:34:21
Advertisements