admin管理员组

文章数量:1394981

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.

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.

Share Improve this question edited Jun 19, 2017 at 11:50 Unnikrishnan asked Jun 19, 2017 at 11:42 UnnikrishnanUnnikrishnan 3,3836 gold badges26 silver badges41 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

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

MDN: https://developer.mozilla/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)

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

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}.`);

本文标签: Making array elements positive in JavascriptStack Overflow