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;
}
}
You approach does not work in this line and the next
because you need to assign the absolute value to the array or a new array at the same index, like
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 forArray#map
.