0

I have the following array in Javascript. I want to find a number to add with every element in this array so that it will only contain positive numbers.

Here I want to shift entire values to positive x - axis in a graph, the graph should look same but it should only in positive x - axis.

['0.000002', '-0.000007', '0.000026', '-0.000043', '-0.000029', '-0.000021', '-0.000023']

Thanks.

3 Answers 3

8

In math terms, you want the absolute value of the number. In JavaScript, that's Math.abs().

MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs

var positiveArray = ['0.000002', '-0.000007', '0.000026', '-0.000043', '-0.000029', '-0.000021', '-0.000023'].map(Math.abs)
console.log(positiveArray)

Sign up to request clarification or add additional context in comments.

4 Comments

You were faster!
you can just use .map(Math.abs), it does the same thing.
Edited with KarlReid's suggestion. Good eye!
Here I want to shift entire values to positive x- axis, the graph should look same but it should only in positive x -axis
2

Use Math.abs absolute value. Remember, this will make the elements in your array numbers while the original array has strings.

var a = ['0.000002', '-0.000007', '0.000026', '-0.000043', '-0.000029', '-0.000021', '-0.000023'];
a = a.map(function(o){
   return Math.abs(o);
});

console.log(a);

Comments

1
const values = ['0.000002', '-0.000007', '0.000026', '-0.000043', '-0.000029', '-0.000021', '-0.000023'];

The objective here is to find a positive number that can be added to each of the items in the array to make them all positive. Hence, the best way to proceed is to find the most negative number in the array. This is done by first mapping all of the stringified numbers into number form. Then, the positive numbers are filtered out. Next, the array is sorted in ascending order. Finally, the first item in the array is the most negative number.

const mostNegativeNumber = values.map(value => +value)
                                 .filter(value => value < 0)
                                 .sort((x, y) => x - y)
                                 .shift();

The answer here is any number that is greater than the opposite of this negative number.

console.log(`Add any number that is greater than ${-mostNegativeNumber}.`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.