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 badges3 Answers
Reset to default 8In 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
版权声明:本文标题:Making array elements positive in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744104620a2591008.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论