简体   繁体   中英

Convert Negative number to floating point

let inputArr = [5,-4,9,-6,7]; 
//expected output is 975.46

I have unsorted array that contains both positive and negative values. Expected output should be descending order of number and negative values should come after dot(.) like floating points. In above example -4 and -6 should come after dot(.) and I am able to achieve array descending sorting but not able to convert negative number as floating point value.

let inputArr = [5,-4,9,-6,7];
let output = inputArr.sort((a,b)=> b-a).join('') 
//output is 975-4-6

You can just replace - as you need in your code.

 let inputArr = [5,-4,9,-6,7]; let output = inputArr.sort((a,b)=> ba).join('').replace('-', '.').replaceAll('-', '') console.log(output)

  • Find the negativeIndex using findIndex .
  • Slice the array positive on one side and negative on another.
  • join both the array.

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

You could sort by sign and join and replace with a counter.

 const array = [5, -4, 9, -6, 7], result = array.sort((a, b) => b - a).join('').replace(/-/g, (i => _ => i++? '': '.')(0)) console.log(result);

This would also work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM