Why do I get NaN from Maths.max? - javascript

So I am trying to get the highest number from the following test cases:
Test.assertEquals(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"), "542 -214");
Test.assertEquals(highAndLow("1 -1"), "1 -1");
Test.assertEquals(highAndLow("1 1"), "1 1");
So far I have the following:
function highAndLow(numbers){
var numbers;
var str;
numbers = numbers.split(' ');
str = numbers.toString();
var a = Math.max(str);
return a;
}
I get NaN. I know the .split is working ok. Could someone help me out please?

Math.max accepts a series of numbers or number as strings (Math.max calls toNumber internally for each argument). The number.toString() is not necessary in your code.
If you want to use Math.max on an arbitrary number of arguments, you can use apply.
Math.max.apply(null, numbersArray);
or spread the array as arguments using the spread operator.
Math.max(...numbersArray);

Math.max expects to be passed multiple arguments, where each argument is a number. You are passing it a string.
You probably want Math.max.apply(Math, numbers) which lets you pass an array of arguments.

When you split the string we get an array of strings. We need to make it array of numbers. For this use map(Number). Then use the following.
function highAndLow(numbers){
var numbers;
var str;
numbers = numbers.split(' ').map(Number);
var a = Math.max.apply(Math, numbers);
return a;
}

Related

what is the difference between .split(" ") and ...array

I am trying to get the max and min numbers from str = "8 3 -5 42 -1 0 0 -9 4 7 4 -4"
The first method gives the correct answer using .min(...arr) but the second method using .min(arr) returns NAN. I thought the spread operator and the split method both created an array that could be passed into Math. What is the difference between the two.
function highAndLow(str){
let arr = str.split(" ")
let min = Math.min(...arr)
let max = Math.max(...arr)
return max + " " + min
}
function highAndLow2(str){
let arr = str.split(" ")
let min = Math.min(arr)
let max = Math.max(arr)
return max + " " + min
}
The Math.min/max functions accept a number as an argument. You can see in the documentation that:
The static function Math.min() returns the lowest-valued number passed into it, or NaN if any parameter isn't a number and can't be converted into one.
That is why, when you don't use the spread operator, you are passing in the array and you are getting NaN as a return value.
The Split operator:
takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
It does something completely different than the Spread operator and is used for other purposes.
I would advise you read more about the Spread operator here.
Math.min does not accept an array,
you need to destructure your array like so :
function highAndLow2(str){
let arr = str.split(" ")
let min = Math.min(...arr)
let max = Math.max(...arr)
return max + " " + min
}
which gives a result of '42 -9'
Math.min() or Math.max() does not accept an array, it is accepted as arguments. The spread operator (...arr) actually expands collected elements such as arrays into separate elements. split(" ") actually converts a string to array. If you want to get min or max value from an array then you have to use apply() like Math.min.apply(null, arr) or Math.max.apply(null, arr)

How to reverse numeric value having scientific notation in nodeJS?

I want to understand best way to reverse an integer (both positive and negative) in NodeJS 12. Can we do this without converting number to string? It should also support scientific notation numbers like 1e+10 which is 10000000000.
Input/Expected Output
500 = 5
-94 = -49
1234 = 4321
-1 = -1
1e+10 = 1
123.45e+10 = 54321
This is the answer I could come up with but I feel there might be better way. I didn't like the way I had to convert the integer to string, reverse it and again convert it back to integer.
parseInt(Math.sign(num) * parseInt(Math.abs(num).toString().split("").reverse().join("")))
function reverseNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
I hope this one line function solves your use-case
// The Math.sign() function returns either a positive or negative +/- 1,
// indicating the sign of a number passed into the argument.
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
}
console.log(reverseInt(500));
console.log(reverseInt(-94));
console.log(reverseInt(1234));

Palindrome creator using javascript and recursion

I need to create a function that takes a number and returns palindrome of this number, by summing its reverse number. For example 312 + 213 = 525. But what's more important, I must use recursion in this situation.
And, for example, number 96 needs like 4 iterations to become 4884.
The strategy is already explained in other comments. Here is a sample recursive JS-implementation that accomplishes your goal:
// Keeps recursively addding the reverse number until a palindrome
// number is obtained
function findPalindrome(num) {
numStr = num.toString();
revNumStr = numStr.split("").reverse().join("");
if (numStr === revNumStr) { // True if palindrome
return num;
} else { // Recursive part
return findPalindrome(num + parseInt(revNumStr))
}
}
console.log(findPalindrome(312));
console.log(findPalindrome(213));
console.log(findPalindrome(96));
You could
get number
convert number to string
get an array of digits
reverse the array
join the array
convert to number
add to original number
convert sum to string
iterate string and check if the value from the beginning is equal to the one at the end
if true return with sum
if false call function again with sum <-- This is the recursion part.

Square every digit of a number

I am trying to learn JavaScript but find it to be a bit confusing. I am trying to square every digit of a number
For example: run 9119 through the function, 811181 will come out, because 9^2 is 81 and 1^2 is 1.
My code:
function squareDigits(num){
return Math.pow(num[0],2) && Math.pow(num[1],2);
}
Correct code:
function squareDigits(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}
I do not know why .map, .split, and .join was used to answer the question.
.split takes a string and splits it into an array based on the character(s) passed to it '' in this case.
So
("9119").split('') === ["9", "1", "1", "9"]
.map works like a for loop but takes a function as an argument. That function is applied to every member of the array.
So
["9", "1", "1", "9"].map(function(val) { return val * val;}) === ["81", "1", "1", "81"]
.join does the opposite of .split. It takes an Array and concatenates it into a string based on the character(s) passed to it.
So
["81", "1", "1", "81"].join('') === "811181"
Additionally, the && operator checks to see if the expressions on either side of it evaluate to true. If both expressions evaluate to true, only then will it return true. It always returns a Boolean though. I think you wanted to convert your values to string first using Number.toString() and then append them together using the + operator
return Math.pow(num[0],2).toString() + Math.pow(num[1],2).toString();
function squareDigits(num) {
// Convert the result to a number. "252525" -> 252525
return Number(
num.toString() // num === "555"
.split('') // ["5", "5", "5"]
.map(elem => elem * elem) "5" * "5" === 25 (Type coversion)
// Now we have [25, 25, 25]
.join('') // "252525"
);
}
squareDigits(555);
There are several methods of this, but the first that comes to mind is to pass the number as a string, split it, then parse the numbers, square them individually, make them strings, and paste them back together, it sounds complex but makes sense once you see it
//function takes number as an argument
function convertNumber(num){
//the toString method converts a number into a string
var number = num.toString();
//the split method splits the string into individual numbers
var arr = number.split("");
//this variable will hold the numbers that we square later
var squaredArr = [];
//the for loop iterates through everything in our array
for(var i=0; i<arr.length; i++){
//parseInt turns a string into a number
var int = parseInt(arr[i]);
//Math.pow raises integers to a given exponent, in this case 2
int = Math.pow(int, 2);
//we push the number we just made into our squared array as a string
squaredArr.push(int.toString());
}
//the function returns the numbers in the squared array after joining
//them together. You could also parseInt the array if you wanted, doing
//this as parseInt(squaredArr[0]); (this would be done after joining)
return squaredArr.join('');
}
Basically you need single digits for getting squared values.
You could take Array.from, which splits a string (which is a type with an implemented Symbol.iterator) into characters and uses an optional maping for the values.
function sqare(number) {
return +Array.from(number.toString(), v => v * v).join('');
}
console.log(sqare(9119));
try these code..
function squareDigits(n) {
return +(n.toString().split('').map(val => val * val).join(''));
}
console.log(squareDigits(4444));
here + sign is convert the string into an integer.

Get first two digits of a string, support for negative 'numbers'

I have the following strings in JavaScript as examples:
-77.230202
39.90234
-1.2352
I want to ge the first two digits, before the decimal. While maintaining the negative value. So the first one would be '-77' and the last would be '-1'
Any help would be awesome!
Thank you.
You can simply use parseInt().
var num = parseInt('-77.230202', 10);
alert(num);
See it in action - http://jsfiddle.net/ss3d3/1/
Note: parseInt() can return NaN, so you may want to add code to check the return value.
Late answer, but you could always use the double bitwise NOT ~~ trick:
~~'-77.230202' // -77
~~'77.230202' // 77
~~'-77.990202' // -77
~~'77.930202' // 77
No octal concerts with this method either.
try this, but you'd have to convert your number to a string.:
var reg = /^-?\d{2}/,
num = -77.49494;
console.log(num.toString().match(reg))
["-77"]
var num = -77.230202;
var integer = num < 0 ? Math.ceil(num) : Math.floor(num);
Also see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math.
Do you just want to return everything to the left of the decimal point? If so, and if these are strings as you say, you can use split:
var mystring = -77.230202;
var nodecimals = mystring.split(".", 1);

Categories

Resources