Square every digit in JavaScript - string * string become a number? - javascript

I am very new to JavaScript and still learning the fundamentals. I was completing a JavaScript challenge were i needed to square every number eg. 881 become 64641. My code is below which i am happy with but I have managed to get myself confused by overthinking.
When i do numArray[i] * numArray[i] as they are both strings does JavaScript automatically convert to a number in order for the numbers to square themselves. Did it turn it into a number - square the number - then turn back into a string again. Which is why i have to do Number(squareArray.join(''));
The reason i ask is I know that if you do string * number it turns to a number, i would if something similar happens. If I am wrong please can someone explain so I can understand.
let numArray = num.toString(); //turn number to a string
let squareArray = []; // create an array to save the new values of the string
for (let i = 0; i < numArray.length; i++) { // iterate through the string
squareArray[i] = numArray[i] * numArray[i]; // save the square of the number to the array
}
return Number(squareArray.join('')); // turn the array into a string and then into a number}

Few observations :
As you want to make a square of a number, why converting those into a string ? Keep it in number form.
As you want each square number element should concat beside each other. You can achieve that only by joining via Array.join('').
Suggestion : Use Array.map() to get square of each number.
Working Demo :
let numArray = [1,2,3,4,5];
const squareArray = numArray.map(item => item * item);
console.log(Number(squareArray.join('')));

Concise one-liner solution
const squareEveryNum = (num) => +Array.from(`${num}`, v => v * v).join("")
Array.from() creates a new shallow-copied Array instance from an iterable or array-like object. e.g Array.from("123") OR Array.from([2,4,5})
Second argument of Array.from() takes callback function to be called on each element of array.
Array.from('223', v => v * v) // [4,4,9]
.join() returns string by concatenating all elements of the array.
+ converts string to number.
Links Array.from(),
Array.join()
References don't have to be [numbers][question].
asd

Related

How to add special characters through the number raw?

I have generated random number. So i want to add some specific places to special characters
As a example - nuzmo2b2yhougkpntd5srif0fdami12_f6gyve0acaddzmt_rbz0iwlizmioiwdmlj
This is the how to genarate random numbers.
let randomkey = [...Array(64)].map(() => Math.random().toString(36)[2]).join('')
console.log(randomkey)
As well as i tried to use splice but it doesn't work
let updatedkey = randomkey.splice(20 , 0 , "_")
This says splice is not a function!
.splice is not a method of string (MDN doc), so to use that, you should convert it to array of character using .split(''), then do .splice, then convert back to string using .join('')
let randomkey = [...Array(64)].map(() => Math.random().toString(36)[2]).join('')
console.log(randomkey)
let updatedkey = randomkey.split('')
updatedkey.splice(20, 0, "_")
updatedkey = updatedkey.join('')
console.log(updatedkey)
You can use JavaScript String slice() method:
let updatedkey = randomkey.slice(0, 20) + "_" + randomkey.slice(20);

Iterate through an array and convert all character codes to characters?

I've coded myself into a hole and though it would be easier to start again, there is still a lesson to be learned here (it's just practice anyway).
I'm building a caesar cipher which will accept two parameters: the message, and the cipher key. Each letter is compared to its corresponding letter in the cipher key, then changed to a new character code.
I'm having a hell of a time figuring out how to turn an array of character codes into an array (or better yet, a string) of characters.
Here's my code:
function cipher(message, cipherKey) {
//convert the message and cipher key to arrays of their character codes
var messageArr = message.toLowerCase().split("").map(x => x.charCodeAt() - 97);
var cipherKeyArr = cipherKey.toLowerCase().split("").map(x => x.charCodeAt() - 97);
//create new array for the ciphered array, which will turn back to a string
var cipheredArr = [];
//loop through both the cipher key value and message key value to
//create the ciphered array
for (var i = 0; i < messageArr.length; i++) {
cipheredArr[i] = messageArr[i] + cipherKeyArr[i];
if (cipheredArr[i] >= 26) {}
}
//go through the ciphered array and make it loop back through
//the alphabet once it goes past z
for (var i = 0; i < cipheredArr.length; i++) {
if (cipheredArr[i] >= 26) {cipheredArr[i] = cipheredArr[i] - 26;}
}
//display on webpage
return cipheredArr;
}
So the cipheredArr is an array of numbers (character codes) but I can't find a good way to iterate through it and change them back into letters. The .fromCharCode() syntax is confusing me for this purpose.
To get an array of characters for an array of character codes, use map:
var chars = codes.map(code => String.fromCharCode(code));
(Note: Just codes.map(String.fromCharCode) won't work, String.fromCharCode would make inappropriate use of the second and third arguments map passes the callback.)
To get a string from those codes:
// ES2015+
var str = String.fromCharCode(...codes);
// ES5 and earlier:
var str = String.fromCharCode.apply(null, codes);
fromCharCode returns a string made up of the code units you pass it as discrete arguments (MDN | spec).

Find out number of numbers present in a comma separated string of numbers in Javascript

I have a requirement to check if some given numbers are Pythogorean triplets.
The textbox accepts string of numbers in the below format:
3,4,5 (comma separated values)
If the user enters more than or three numbers an error alert is displayed. My team mate figure out a way to do this , but accidentally. How does the below method work?
function CheckNumbers(strnum){
var num = strnum.split(",")
if(num.length != 3)
{
alert(Enter exactly three numbers!)
return;
}
}
Should'nt it return the length of the string rather than the number of numbers?
As I read it, the input parameter strnum gets split by "," into an array, and num.length returns the length of the array.
No, The above code is right what it does is to break string in to an array and than return the length of that array
strnum = 1,2,3;
num = strnum.split(",") // num = [1,2,3]
num.length // 3
Your case is you are using a Number, and replace is associated to String.
Try to cast it before.
strnum = "1,2,3";
num = strnum.split(",") // num = [1,2,3]
num.length // 3

Parse a string representing an array of floats

I have a string as such:
string = "[x,y,z]"
Where x, y and z are valid javascript floats as strings. Some examples:
-0.9999
1.
1.00000000000E-5
-1E5
What is the most efficient (fastest) way to parse this string into an actual javascript array of floats without using Eval?
Now I do this:
parseFloatArray = function(string){
// isolate string by removing square brackets
string = string.substr( 1, string.length-2 )
// create array with string split
var array = string.split(',');
// parse each element in array to a float
for (var i = 0, il = array.length; i < il; i++){
array[i] = parseFloat(array[i]);
}
// return the result
return array
}
It is important that the solution works correctly for the above examples.
I also tried with JSON.parse which seemed perfect at first, but it returns a SyntaxError for the second example 1. where there is nothing following the decimal separator.
I prepared a fiddle for testing.
Instead of this
array[i] = parseFloat(array[i]);
try
array[i] = +array[i];
Above handles all the test cases pretty well.
Here is the working fiddle
Try this :
str = "[-0.9999, 1., 1.00000000000E-5,-1E5]";
str.slice(1, str.length-1).split(',').map(Number);
// [-0.9999, 1, 0.00001, -100000]
parseFloat basic syntax is parseFloat(string). https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
If you think the input values are only numbers you can use Number(x) rather than parseFloat.
Also, you might get different values upon parsing because all floating-point math is based on the IEEE [754] standard. so use toPrecision() method to customize your values- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision.
Instead of you writing the for loop, you can always use the javascript built in array.prototypes
var string = "[1.,-0.9999,-1.00000E-5]";
var array = string.substr( 1, string.length-2 ).split(',');
console.log(array.map(function(i){return parseFloat(i);}));
you can also use the unary operator instead of parseFloat().
console.log(array.map(function(i){return +i;}));
Most efficient to extract is replacing and splitting.
var str = "[312.413,436.6546,34.1]"; // string
str = () => str.replace(/\[|\]/g, "").split(","); //[312.413, 4...] Array
most eficient to parse is just preceed the string with a "+", that will numerify it and, since javascript works with floats as primitives (and not integers), they will be automatically parsed.
var a = "1.00000000000E-5";
console.log( +a ); // 0.00001

Count the elements in string

I have a string that has comma separated values. How can I count how many elements in the string separated by comma?
e.g following string has 4 elements
string = "1,2,3,4";
myString.split(',').length
var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;
All of the answers suggesting something equivalent to myString.split(',').length could lead to incorrect results because:
"".split(',').length == 1
An empty string is not what you may want to consider a list of 1 item.
A more intuitive, yet still succinct implementation would be:
myString.split(',').filter((i) => i.length).length
This doesn't consider 0-character strings as elements in the list.
"".split(',').filter((i) => i.length).length
0
"1".split(',').filter((i) => i.length).length
1
"1,2,3".split(',').filter((i) => i.length).length
3
",,,,,".split(',').filter((i) => i.length).length
0
First split it, and then count the items in the array. Like this:
"1,2,3,4".split(/,/).length;
First You need to convert the string to an array using split, then get the length of the array as a count, Desired Code here.
var string = "1,2,3,4";
var desiredCount = string.split(',').length;

Categories