Make all numbers in array Absolute value in Javascript

3.5k views Asked by At

I'm trying to make all values in the below array absolute, after trying several methods the results that appears is 5 the first element in the array. the below is the code given:

describe('absoluteValueArray', () => {
    it('Gets multiple absolute values', () => {
      const result = absoluteValueArray([-5,-50,-25,-568])
      expect(result).toEqual([5,50,25,568])
    })
  })

Function I tried is the below:

const absoluteValueArray = (array) => {

    var index, len;
    var array = ["-5", "-50", "-25" , "-568"];
    for (index = 0, len = array.length; index < len; ++index) {
      let res = Math.abs(array[index]);
      return res;
    }

}
1

There are 1 answers

0
Nina Scholz On BEST ANSWER

You approach does not work in this line and the next

let res = Math.abs(array[index]);
return res;

because you need to assign the absolute value to the array or a new array at the same index, like

resultArray[i] = Math.abs(array[index]);

and return the array after finishing the loop.

The original return inside of the loop exits the loop with the first element.


Instead, you could take Math.abs as callback for Array#map.

const absoluteValueArray = (array) => {
    return array.map(Math.abs);
}

console.log(absoluteValueArray([-5, -50, -25, -568]));