Computer >> Computer tutorials >  >> Programming >> Javascript

Inverting signs of integers in an array using JavaScript


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 −

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 ]