Home > Software design >  Convert Negative Numbers in Array
Convert Negative Numbers in Array

Time:07-21

const numbers = [200, 450, -400, 3000, -650, -130, -70, 1300];

I want all negative numbers in this array to be Positive. How can I do that using Javascript?

//OUTPUT const numbers = [200, 450, 400, 3000, 650, 130, 70, 1300];

CodePudding user response:

How about using map with Math.abs() to get the number's absolute value?

const notNegative = numbers.map((num) => Math.abs(num));

Since OP asked, you can use forEach, too, but you'd need to push results to a second array:

let notNegative = [];
numbers.forEach((num) => notNegative.push(Math.abs(num)));

CodePudding user response:

You can write it even shorter:

const arr=[200, 450, -400, 3000, -650, -130, -70, 1300];

console.log(arr.map(Math.abs));

CodePudding user response:

You can use absolute provided by Math as Math.abs() to convert all number into absolute number i.e. on positive side (whole number)

const numbers = [200, 450, -400, 3000, -650, -130, -70, 1300];
output=numbers.map(e=>Math.abs(e))
console.log(output)
// [200, 450, 400, 3000, 650, 130, 70, 1300]

CodePudding user response:

You can use the Array#forEach and numbers[i] = ... if you do not want to create a new array; by definition the Array#map method creates a new array.

const numbers = [200, 450, -400, 3000, -650, -130, -70, 1300];

numbers.forEach((elm,i) => numbers[i] = elm < 0 ? -elm : elm);
//OR numbers.forEach((elm,i) => numbers[i] = Math.abs(elm));

console.log( numbers );

  • Related