Using sort() to get numbers in descending order - javascript

I'm trying to complete this kata. Trying to figure it out, I've seen this thread but I think I'm doing it as it says in there.
What am I doing wrong? Why doesn't it sort the numbers in descending order?
This is my code so far:
function descendingOrder(n){
let newN = n.toString().split(' ').sort(function(a,b){return b-a}).join();
return parseInt(newN);
}
Test Passed: Value == 0
Test Passed: Value == 1
Expected: 987654321, instead got: 123456789
Thanks in advance

You need to split the string with an empty string '' to get single digits and join it with an empty string.
Splitting with a character which is not part of the string results in an array with a single value. A later joined array returns this single element. That is why you get the same value as result as the input.
Array#join without a specified separator, returns a comma separated string with the values.
let newN = n.toString().split('').sort(function (a, b) { return b - a; }).join('');
At the end, you could take an unary plus +, like
return +newN;
for getting an numerical value.
BTW, with the use of parseInt, you may specify a radix, because strings with leading zero may be converted to an octal number.

Here is an explained answer
function descendingOrder(n) {
let result = n
.toString() // convert numbers to string
.split('') // split each string char in to an array of chars
.sort((a, b) => b - a) // sort that array descending
.join('') // regroup all items in that array into 1 string
return parseInt(result) // turn the group of strings into an array
}

function descendingOrder(n){
return +('' + n).split('').sort().reverse().join('');
}

Like the other answers have already stated you will need to call split with an empty string to properly create an array containing each character.
Also, when I tested join() I noticed commas in the output (chrome 65). I added a replace function to strip the commas, which passed the test.
function descendingOrder(n){
let newN = n.toString().split('').sort(function(a,b){return b-a}).join().replace(/,/g,'');
return parseInt(newN);
}

Related

Want to convert big numbers into exact number string

const num = 100000000000000000000001
console.log(num.toString()) //1.0000000000000001e+23
console.log(num.toLocaleString('fullwide', { useGrouping: false })) //100000000000000010000000
I want to convert num in to exact string like 1000000000000000000001. I tried these two methods but non of them works. At last I want to split these individual digits into an array and array doesn't works on number that's why i want to convert it to exact string.
Since ECMAScript 2020 you can use bigint data type, which will have a toString() method that works as you want it.
// note the "n" which denotes this is a bigint
const num = 100000000000000000000001n;
// verify it's a bigint
console.log(typeof num);
// print the number
console.log(num.toString());
// put inidividual digits in array
console.log(num.toString().split(""));

Why do trailing and leading zeros cause my function to return values i do not want?

This set of code i am providing should take any number i enter and reverse it. Currently the function works when n = 21.365 or n = 5698 but when n = 0456456456 it returns 41422397 instead of 6546546540 or when n = 056985 it returns 58965 instead of 589650 and when n = 016540 it returns 257 instead of 45610.
This is what i have written so far
//rules & limitations
//negative numbers should remain negative
//leading zeros should be removed
//the function can accept floats or integers
//the function will return integers as integers
function reverseNumberWithBuiltInFunctions(n) {
return (
parseFloat (
n
//convert the number to a string
.toString()
//convert to array of characters
.split('')
//reverse array of characters
.reverse()
//join reversed array of characters
.join('')
) * Math.sign(n)
)
}
I would like if n = 001 then 100 is returned or if n = 0456456456 then 6546546540 is returned. Essentially i am having trouble when leading or trailing zeros or both are included in "n" or it seems like issues arise when there is some sort of pattern to the numbers.
Also, why is it that when n = 016540 it returns 257?
Do you know of any solutions that could help improve the logic of the function with the given rules and limitations that would yield the desired results?
What you want is impossible if the inputs are integers or floats. There is no such thing as "leading zeros" on either integers or floats. If you use leading zeros to make a integer literal, it becomes an octal literal (changing the value; that's why n = 0456456456 behaves the way it does, 0456456456 is just the octal way to spell 79322414). If you parse a string with leading zeros to make an integer, they're simply ignored (parseInt('000123') produces the same value as parseInt('123'), namely, the value 123). That's why 016540 becomes 257: the octal literal is equivalent to the decimal literal 7520, and reversing it and parsing back to integer ignores the leading 0, leaving 257.
You can't preserve such leading zeros because they don't exist outside of string form. And you'll lose the trailing zeros on reversal because they become leading zeros in the new form.
Either work with strings exclusively, or accept that you'll lose leading zeros.
I'll note that your own rules in the comments specify:
//leading zeros should be removed
so it's working as expected here.
You have to pass it in as a string as leading 0's in your numbers will not be interpreted as such.
For example:
// Will always be evaluated as 1
let foo = 001;
console.log(foo);
If you were to supply n as a string, you may do it like this:
reverseNumberWithBuiltInFunctions = n => parseFloat(n.toString().split('').reverse().join(''));
console.log(reverseNumberWithBuiltInFunctions('0456456456'))
console.log(reverseNumberWithBuiltInFunctions('056985'))

D3 parse number from string

I am new to using D3.js and I am having problems converting string data into a number. I am using a CSV with one column called "Belgium" composed by numbers like these ones: 54,345 or 1,234,567.
I tried to convert them into numbers by using
data.forEach(function(d) {
d.Belgium = +d.Belgium;
}
but I get NaN as a result. I also tried using
d.Belgium = parseInt(d.Belgium);
but it takes the figures before the first comma and removes the rest of the number. For example, if one number is 1,234,562, using parseInt() I just get 1. If the figure is 982,381, it remains 982.
Remove all , with string.replace(searchvalue, newvalue):
parseInt(str.replace(/,/g, ""))
so for example:
console.log(parseInt("1,234,562".replace(/,/g, "")))
As noted below, use parseFloat instead of parseInt if your numbers may contain decimals e.g. 3.141,592 to keep the floating point number.
I took a bit of a different approach. I used .split(",") to split the value into an array at every ,, then used .join("") to join each index of the array with empty spaces. Used the + operator for ease of use but could have been parseFloat() as well.
let stringNumber = "1,250,234.093";
let numStringNumber = +stringNumber.split(",").join("");
console.log(numStringNumber);
console.log(typeof numStringNumber);

Why does parseInt fail to test Arrays properly in Javascript?

Given:
var obj={0:21,1:22}
and
var arr=[21,22]
Why does parseInt(obj) return NaN, but parseInt(arr) returns 21?
I had a function where I was either going to pass an int, a hash type object or a plain array. I was expecting parseInt to return NaN for both object and array, thus simplifying argument checking. What gives?
This is because parseInt tries to coerce the first argument to a string before parsing to an integer. String(obj) returns "[object Object]" and can't be parsed, but String([21,23]) returns "21,23", which parseInt parses until it reaches the unparseable char.
See the parseInt spec:
Let inputString be ? ToString(string).
(Coerce the input to a string).
If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.
(Drop any part of the string starting with non-digit character, so "21,23" -> "21").

time complexity for comparing two strings

How is the running time of the ff function o(nlogn)?
function isPermutation(a, b) {
if (a.length !== b.length) {
return false;
}
return a.split("").sort().join() === b.split("").sort().join();
}
aren't you checking the length of both strings, or is it dependent on the implementation of sort?
According to definition of Permutation, a String is permutate of another String if and only if all chars in the first String are also in the second String.
Example: "answer" is permutate of "awerns".
So to write an algorithm that checks if one string is permutate of another string all you have to do is:
Check if length of the two strings is same, return false if they are not same.
For each letter in String one check if it also exists in String two.
The above algorithm's running time will be but you can use sorting to solve same problem:
Check if length of two strings is same, return false if they are not same.
Sort the two strings
Each char in the Strings sequentially, like stringOne[i] == stringTwo[i]
So in this one if you use good sorting algorithm like Quick Sort or Merge Sort the overall running time will be

Categories