I have an integer and want to create an array from each of its numbers.
let interget = 345;
//I want create the array [3,4,5]
Is there any easy way to do this using Array.from() or would I need to convert the number to a string first?
easy way by converting to string
(inputNumber + "").split("").map(char => +char)
basically we split string and convert each character back to number
doing it manually
function getDigits(n) {
const ans = [];
while(n > 0){
let digit = n % 10;
ans.push(digit);
n -= digit;
n /= 10;
}
return ans.reverse();
}
Or you can do it like this:
var result = Array.from('345', Number)
console.log(result);
Related
I have an integer containing various digits, I want to remove 4th digit from an integer. How can I achieve that ?
Example :
let number = 789012345
Here I want to remove 0
Try this :
// Input
let number = 789012345;
// Convert number into a string
let numberStr = number.toString();
// Replace the 0 with empty string
const res = numberStr.replace(numberStr[3], '');
// Convert string into a number.
console.log(Number(res));
Rohìt Jíndal's answer is excellent. I just want to point out another way you could do this with string.replace and capturing groups.
function removeDigit(input, index) {
let exp = new RegExp(`^(\\d{${index}})(\\d)(.+)$`);
return parseInt(input.toString().replace(exp, '$1$3'));
}
let output = removeDigit(789012345, 3);
console.log(output); // 78912345
In this example, I have created a new RegExp object from a template literal in order to inject the index.
The first capturing group contains all digits up to the desired index. The second contains the digit we want to remove and the third contains the remainder of the string.
We then return an integer parsed from the string combination of only the first and third capturing groups.
You can follow this procedure:
Decide if you want to remove digits by index or by value, the following demo will remove by value, which means it will remove all values that match
Convert the number into a string
Convert the string to an array with Array.from
Use Array#filter to remove target digit(s)
Use Array#join to create a string
Use + to convert to string back into a numeric value
const n = 789012345;
const m = +Array.from( n.toString() ).filter(num => +num !== 0).join("");
console.log( m );
let numberWithoutADigit = removeIthDigitFromNumber(789012345, 4);
function removeIthDigitFromNumber(n, i){
//convert the number n to string as an array of char
let o = (n + '').split('');
//remove the item at the index i (0 based) from the array
o.splice(i, 1);
//rebuilds the string from the array of char and parse the string to return a number
let number = parseInt(o.join(''));
return number;
}
let number = 789012345
let i = 3 // index 3, 4th digit in number
let arr = number.toString().split("").filter((value, index) => index!==i);
// ['7', '8', '9', '1', '2', '3', '4', '5']
let new_number = parseInt(arr.join(""))
// 78912345
console.log(new_number)
let x = 789012345
var nums = [];
let i = 0, temp = 0;
while(x > 1){
nums[i++] = (x % 10);
x = (x - (x % 10)) / 10;
}
var cnt = 0;
for(--i; i >= 0; i--){
if (cnt++ == 3) continue;
temp = temp * 10 + nums[i];
}
I don't know what is the right question for this.
I want to make this number -800 become [-8,0,0] is anyone can build it
The first thing that I do, is to make the number become a string and using the map function I iterate it becomes an array like this
const number = -800;
const numberString = number.toString();
const arrayString = numberString.split``.map((x) => +x);
console.log(arrayString)
But the result is [ NaN, 8, 0, 0 ]
How to change the NaN and first index 8 become -8 without disturbing the other index. So it becomes [-8, 0, 0]
Is anybody can help me?
Thanks.
Try numberString.match(/-?\d/g) instead of split
const number = -800;
const numberString = number.toString();
const arrayString = numberString.match(/-?\d/g).map(x => +x);
console.log(arrayString)
One possible solution is to just do this operation on the absolute value and, during the map, check if the number was negative (only for the first index).
const number = -800;
const numberString = Math.abs(number).toString();
const arrayString = numberString.split``.map((x, i) => i == 0 && number < 0 ? -x : +x);
console.log(arrayString)
If you're not clear about Regex, you can use Array.from to convert a string to an array number. Then handle the first number based on the sign of original number.
console.log(convertNumberToArray(800));
console.log(convertNumberToArray(-800));
function convertNumberToArray(number){
var result = Array.from(Math.abs(number).toString(), Number);
result[0] *= number <= 0 ? -1 : 1;
return result;
}
Use String#match with regex which matches optional - with the dig it.
var number = -800;
var numberString = number.toString().match(/-?\d/g);
var numberInt = [];
for (var i = 0; i < numberString.length; i++) {
numberInt.push(parseInt(numberString[i]));
}
console.log(numberInt);
I was given the challenge of converting a string of digits into 'fake binary' on Codewars.com, and I am to convert each individual digit into a 0 or a 1, if the number is less than 5 it should become a 0, and if it's 5 or over it should become a 1. I know how to analyze the whole string's value like so:
function fakeBin(x){
if (x < 5)
return 0;
else return 1;
}
This however, analyzes the value of the whole string, how would I go about analyzing each individual digit within the string rather than the whole thing?
Note: I have already looked at the solutions on the website and don't understand them, I'm not cheating.
You can do it in one line with two simple global string replacement operations:
function fakeBin(x){
return ("" + x).replace(/[0-4]/g,'0').replace(/[5-9]/g,'1');
}
console.log(fakeBin(1259))
console.log(fakeBin(7815))
console.log(fakeBin("1234567890"))
The ("" + x) part is just to ensure you have a string to work with, so the function can take numbers or strings as input (as in my example calls above).
Simple javascript solution to achieve expected solution
function fakeBin(x){
x = x+'' ;
var z =[];
for(var i=0;i< x.length;i++){
if((x[i]*1)<5){
z[i] =0;
}else{
z[i]=1;
}
}
return z
}
console.log(fakeBin(357))
The snippet below will take a string and return a new string comprised of zeros and/or ones based on what you described.
We use a for ...of loop to traverse the input string and will add a 0 or 1 to our return array based on whether the parsed int if greater or less than 5.
Also note that we are checking and throwing an error if the character is not a number.
const word = "1639";
const stringToBinary = function(str) {
let ret = [];
for (const char of word) {
if (Number.isNaN(parseInt(char, 10))) {
throw new Error(`${char} is not a digit!`);
} else {
const intVal = parseInt(char, 10);
ret.push(intVal > 5 ? 1 : 0);
}
}
return ret.join('');
};
console.log(stringToBinary(word));
if you are in java you can use
charAt()
and you make a for with the word length and you can check one by one
for(int i = 0; i < text.length(); i++){
yourfunction(texto.charAt(i));
}
Split the string and apply the current function you have to each element of the string. You can accomplish this with map or with reduce:
function fakeBin(x) {
x = x.split('');
let toBin = x => {
if (x < 5)
return 0;
else return 1
}
return x.map(toBin).join('');
}
console.log(fakeBin("2351"));
refactored
function fakeBin(x) {
x = [...x];
let toBin = x => x < 5 ? 0 : 1;
return x.map(toBin).join('');
}
console.log(fakeBin("2351"));
reduce
function fakeBin(x) {
let toBin = x => x < 5 ? 0 : 1;
return [...x].reduce((acc,val) => acc + toBin(val), "");
}
console.log(fakeBin("23519"));
You can use String.prototype.replace() with RegExp /([0-4])|([5-9])/g to match 0-4, 5-9, replace with 0, 1 respectively
let str = "8539734222673566";
let res = str.replace(/([0-4])|([5-9])/g, (_, p1, p2) => p1 ? 0 : 1);
console.log(res);
I want to know if a string with integer data can be converted to a CryptoJS word array correctly?
Example. Can I convert "175950736337895418" into a word array the same way I can create a word array out of 175950736337895418 (int value).
I have some code that converts integer values to word array
// Converts integer to byte array
function getInt64Bytes( x ){
var bytes = [];
for(var i = 7;i>=0;i--){
bytes[i] = x & 0xff;
x = x>>8;
}
return bytes;
}
//converts the byte array to hex string
function bytesToHexStr(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join("");
}
// Main function to convert integer values to word array
function intToWords(counter){
var bytes = getInt64Bytes(counter);
var hexstr = bytesToHexStr(bytes);
var words = CryptoJS.enc.Hex.parse(hexstr);
return words;
}
Even this code doesn't work correctly as very large integer numbers (exceeding javascript limit of numbers 2^53 - 1) get rounded off. Hence I wanted a solution that could take the integer value as string and convert it to a word array correctly.
PS. I need this word array to calculate the HMAC value using the following code
CryptoJS.HmacSHA512(intToWords(counter), CryptoJS.enc.Hex.parse(key))
What you want is to parse big numbers from strings. Since this is necessary for RSA, you can use Tom Wu's JSBN to get that functionality. Be sure to include jsbn.js and jsbn2.js. Then you can use it like this:
function intToWords(num, lengthInBytes) {
var bigInt = new BigInteger();
bigInt.fromString(num, 10); // radix is 10
var hexNum = bigInt.toString(16); // radix is 16
if (lengthInBytes && lengthInBytes * 2 >= hexNum.length) {
hexNum = Array(lengthInBytes * 2 - hexNum.length + 1).join("0") + hexNum;
}
return CryptoJS.enc.Hex.parse(hexNum);
}
var num = "175950736337895418";
numWords = intToWords(num);
document.querySelector("#hexInt").innerHTML = "hexNum: " + numWords.toString();
document.querySelector("#hexIntShort").innerHTML = "hexNumShort: " + intToWords("15646513", 8).toString();
var key = CryptoJS.enc.Hex.parse("11223344ff");
document.querySelector("#result").innerHTML = "hexHMAC: " +
CryptoJS.HmacSHA512(numWords, key).toString();
<script src="https://cdn.rawgit.com/jasondavies/jsbn/master/jsbn.js"></script>
<script src="https://cdn.rawgit.com/jasondavies/jsbn/master/jsbn2.js"></script>
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/hmac-sha512.js"></script>
<div id="hexInt"></div>
<div id="hexIntShort"></div>
<div id="result"></div>
If you need the result in a specific length, then you can pass the number of required bytes as the second argument.
I want to Split a number into its digit (for example 4563 to 4 , 5 , 6 , 3 ) then addiction this digits. (for example: 4+5+6+3=18)
I can write code for 3 digit or 2 digit and ... numbers seperately but I cant write a global code for each number.
so this is my code for 2 digit numbers:
var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5
and this is my code for 3 digit numbers:
var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15
but I cant write a code to work with each number.How can I write a global code for each number?
In modern browsers you can do an array operation like
var num = 4563;
var sum = ('' + num).split('').reduce(function (sum, val) {
return sum + +val
}, 0)
Demo: Fiddle
where you first create an array digits then use reduce to sum up the values in the array
var num = 4563;
var sum = 0;
while(num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
console.log(sum);
Do number%10(modulus) and then number/10(divide) till the number is not 0
I hope the following example is useful to you:
var text="12345";
var total=0;
for (i=0;i<text.length;i++)
{
total+= parseInt(text[i]);
}
alert(total);
This solution converts the number to string, splits it into characters and process them in the callback function (prev is the result from the previous call, current is the current element):
var a = 456;
var sum = a.toString().split("").reduce(function(prev, current){
return parseInt(prev) + parseInt(current)
})
Here is how I would approach the problem. The trick I used was to split on the empty string to convert the string to an array and then use reduce on the array.
function digitSum(n) {
// changes the number to a string and splits it into an array
return n.toString().split('').reduce(function(result, b){
return result + parseInt(b);
}, 0);
}
As mentioned by several other posters (hat tip to my commenter), there are several other good answers to this question as well.
Here is my solution using ES6 arrow functions as call back.
- Convert the number into a string.
- Split the string into an array.
- Call the map method on that array.
- Callback function parse each digit to an array.
let number = 65535;
//USING MAP TO RETURN AN ARRAY TO DIGITS
let digits = number.toString()
.split("")
.map(num => parseInt(num));
//OUTPUT TO DOM
digits.forEach(
digit =>
document.querySelector("#out").innerHTML += digit + "<br>"
);
<p id="out"></p>
1) You can cast input number to string, using .toString() method and expand it into array with spread (...) operator
const splitNumber = n => [ ...n.toString() ]
2) Another short way - using recursion-based solution like:
const splitNumber = n => n ? [ ...splitNumber(n/10|0), n%10 ] : []