In JavaScript, you can convert all numbers in an array of numbers to their absolute form, for example, in the following way:
// ES6+ const arr = [1234, -5678, 12.34, -56.78]; const newArr = arr.map((num) => Math.abs(num)); console.log(newArr); // [1234, 5678, 12.34, 56.78]
This works by calling the Math.abs()
function on every element of the array using the Array.prototype.map()
method.
You can rewrite the callback to Array.prototype.map()
without arrow function to make it compatible with ES5.
If the array can potentially have bigint values as well, then Math.abs()
will not work. In that case, you can do the following:
// ES10+ const arr = [-1234n, -5678, 12.34, -56.78]; const newArr = arr.map((num) => (num < 0n) ? -num : num); console.log(newArr); // [1234n, 5678, 12.34, 56.78]
The examples above would create a new array with all numbers in the array in absolute form. You can achieve the same with a simple for
loop as well:
const arr = [1234, -5678, 12.34, -56.78]; const newArr = []; for (let i = 0; i < arr.length; i++) { newArr.push(Math.abs(arr[i])); } console.log(newArr); // [1234, 5678, 12.34, 56.78]
Or, you can use the following code if the array can have bigint values as well:
// ES10+ const arr = [-1234n, -5678, 12.34, -56.78]; const newArr = []; for (let i = 0; i < arr.length; i++) { const num = arr[i]; newArr.push((num < 0n) ? -num : num); } console.log(newArr); // [1234n, 5678, 12.34, 56.78]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.