1

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;
    }

}
Nad.E.S
  • 49
  • 1
  • 7
  • 4
    please add at least one try. – Nina Scholz Oct 07 '20 at 08:19
  • 3
    _"after trying several methods the results that appears is somethimes NaN"_ - None of them are in your "question" -> [mcve] – Andreas Oct 07 '20 at 08:19
  • Part of the [mre] is the *output* - in this case presumably the test is failing because the output is just `5`, which should give you a clue about what the problem is, but please include it in the question. – jonrsharpe Oct 07 '20 at 08:25
  • done, I edited my post. – Nad.E.S Oct 07 '20 at 08:26
  • After having added one of the several attempts: what have you tried to check **why** this does not worko? As a hint: why did you put a `return` statement in the `for` loop? – Nico Haase Oct 07 '20 at 15:24
  • @NicoHaase You can't expect OP to have that knowledge, nor does it add any value to the question. Please note that "Not enough effort" is not a close reason, as has been discussed on Meta _many_ times before. ([1](https://meta.stackoverflow.com/q/260828/479156), [2](https://meta.stackoverflow.com/q/253069/479156), [3](https://meta.stackoverflow.com/q/253137/479156), [4](https://meta.stackoverflow.com/q/270903/479156), [5](https://meta.stackoverflow.com/q/251775/479156)) – Ivar Oct 08 '20 at 10:01

1 Answers1

3

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]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392