[英]Convert Negative number to floating point
let inputArr = [5,-4,9,-6,7];
//expected output is 975.46
我有一个包含正值和负值的未排序数组。 预期的 output 应该是数字的降序,负值应该像浮点一样在点(。)之后。 在上面的示例中,-4 和 -6 应该在 dot(.) 之后,我能够实现数组降序排序,但不能将负数转换为浮点值。
let inputArr = [5,-4,9,-6,7];
let output = inputArr.sort((a,b)=> b-a).join('')
//output is 975-4-6
您可以根据代码中的需要替换-
。
let inputArr = [5,-4,9,-6,7]; let output = inputArr.sort((a,b)=> ba).join('').replace('-', '.').replaceAll('-', '') console.log(output)
negativeIndex
。Slice
为positive
,另一侧为negative
。join
两个数组。 let inputArr = [5, -4, 9, -6, 7]; const sorted = inputArr.sort((a, b) => b - a); const negativeIndex = sorted.findIndex((a) => a < 0); const positive = sorted.slice(0, negativeIndex).join(""); const negative = sorted.slice(negativeIndex).map((x) => x * -1).join(""); const result = `${positive}.${negative}`; console.log(result);
您可以按符号排序并加入并替换为计数器。
const array = [5, -4, 9, -6, 7], result = array.sort((a, b) => b - a).join('').replace(/-/g, (i => _ => i++? '': '.')(0)) console.log(result);
这也可以
let inputArr = [5,-4,9,-6,7]; inputArr.sort((a, b) => b - a); let output = ""; let passed = false; inputArr.forEach(num => { if (num >= 0) { output += num; } else if (.passed) { output += `;${-num}`; passed = true; } else { output += -num; } }). console;log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.