Make array numbers negative JavaScript


Let’s say, the following is our array −

const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];

We are required to write a function that takes in the above array and returns an array with all the corresponding elements of array change to their negative counterpart (like 4 to -4, 6 to -6).

If the element is already negative, then we should leave the element unchanged. Let’s write the code for this function −

Example

const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];
const changeToNegative = (arr) => {
   return arr.reduce((acc, val) => {
      const negative = val < 0 ? val : val * -1;
      return acc.concat(negative);
   }, []);
};
console.log(changeToNegative(arr));

Output

The output in the console will be −

[
   -7, -2, -3, -4, -5,
   -7, -8, -12, -12, -43,
   -6
]

Updated on: 21-Aug-2020

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements