Converting String to Number in Javascript - javascript

I'm stuck in small problem where I'm trying to convert String to number but that String number is huge due to which it is not properly converting to number type.
str = "6145390195186705543"
num = Number(str)
digits = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
let str = String(Number(digits.join(''))+1).split('')
after performing above operation the value of num is 6145390195186705000 which is not what I was expecting. It should be 6145390195186705543.
It would be very helpful if someone can explain this and tell if there is any alternative way.
I have tried parseInt() and '+' as well but nothing is working.

If you want to increment an array of integer values, you can join the digits and pass it to the BigInt constructor. After it is a BigInt, you can add 1n. Once you have added the value, you can stringify the value and split it. Lastly, you can map each digit back into an integer.
const digits = [6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3];
const str = (BigInt(digits.join('')) + 1n).toString().split('').map(digit => +digit);
console.log(JSON.stringify(str)); // [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
Here is the code above, modified into a function:
const numArrayAdd = (bigIntSource, bigIntAmount) =>
(BigInt(bigIntSource.join('')) + bigIntAmount)
.toString().split('').map(digit => +digit);
const digits = [6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 5, 5, 4, 3];
const str = numArrayAdd(digits, 1n);
console.log(JSON.stringify(str)); // [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]

you can add just a + right before that variable
here is a good example about that
https://youtu.be/Vdk18Du3AVI?t=61

Related

why it is returning only false? Luhn algorithm

What's wrong with my code? It should return true for this array. The invalid one should return false.
Please explain it to me because i'm just started with JS
//arrays :
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];
const validateCred = Array => {
let cardNum = 0
let reverseArray = Array.reverse()
for (let i = 0; i < reverseArray.length; i++){
let newVar = reverseArray[i]
if (i%2 !== 0){
newVar = reverseArray[i] * 2
if (newVar > 9){
newVar = newVar[i] - 9;
cardNum += newVar
} else {
cardNum += newVar
}
} else {
cardNum += reverseArray[i]
}
}
return(cardNum%10 === 0 ? true : false)
}
console.log(validateCred(valid1))
As you figured out and noted in the comments, this is not going to go well when newVar is a number:
newVar = newVar[i] - 9;
And as Pointy, um, pointed out, Array is a terrible name for a variable, shadowing an important constructor function. More than that, there is a strong convention in JS that InitialCapital variable names are reserved for constructor functions. I would suggest a name that describes what it's for, not its type. Perhaps "creditCard" would be useful, or, depending on your tolerance for short abbreviations, "cc".
But there's another, more subtle, problem with this code. It alters its input:
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
console .log (validateCred (valid1)) //=> true
console .log (valid1) //=> [8, 0, 8, 6, 1, 0, 8, 0, 9, 7, 7, 6, 9, 3, 5, 4]
In a real application, this could cause you all sorts of problems, and maybe far away from this section, always frustrating.
It's easy enough to fix. Just clone the array before reversing it. There are many ways to do it (using myVariable.slice() or myVariable.concat(), for instance.) My preference these days is to spread it into a new array: [...myVariable].
In my answer to another Luhn's Algorithm question, I developed what I think of as an elegant version of this algorithm. If you're new to JS, this may use some features you're not familiar with, but I find it clear and useful. This is a slightly improved version:
const luhn = (ds) => ([...ds]
.filter(d => /^\d$/ .test (d))
.reverse ()
.map (Number)
.map ((d, i) => i % 2 == 1 ? (2 * d > 9 ? 2 * d - 9 : 2 * d) : d)
.reduce ((a, b) => a + b, 0)
) % 10 == 0
It's the same algorithm, just expressed a little more concisely. Between the spreading of the initial value and the filter call (removing non-digits), it allows us to pass various input formats:
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const valid2 = "4539677908016808"
const valid3 = "4539-6779-0801-6808"
const valid4 = "4539 6779 0801 6808"

does python have an equivalent to javascript's every and some method?

I was trying to search the docs for a method similar but I was only able to find pythons all() and any(). But that's not the same because it just checks if the val is truthy instead of creating your own condition like in js' every and some method.
i.e
// return true if all vals are greater than 1
const arr1 = [2, 3, 6, 10, 4, 23];
console.log(arr1.every(val => val > 1)); // true
// return true if any val is greater than 20
const arr2 = [2, 3, 6, 10, 4, 23];
console.log(arr2.some(val => val > 20)); // true
Is there a similar method that can do this in python?
Just combine it with a mapping construct, in this case, you would typically use a generator expression:
arr1 = [2, 3, 6, 10, 4, 23]
print(all(val > 1 for val in arr1))
arr2 = [2, 3, 6, 10, 4, 23]
print(any(val > 20 for val in arr2))
Generator comprehensions are like list comprehensions, except they create a generator not a list. You could have used a list comprehension, but that would create an unecessary intermediate list. The generator expression will be constant space instead of linear space. See this accepted answer to another question if you want to learn more about these related constructs
Alternatively, albeit I would say less idiomatically, you can use map:
arr1 = [2, 3, 6, 10, 4, 23]
print(all(map(lambda val: val > 1, arr1)))
arr2 = [2, 3, 6, 10, 4, 23]
print(any(map(lambda val: val > 20, arr2)))
Yes, Python has it.
numbers = [1, 2, 3, 4, 5]
all_are_one = all(elem == 1 for elem in numbers)
some_are_one = any(elem == 1 for elem in numbers)

Sorting an array of numbers based on start and end values [duplicate]

This question already has answers here:
Sort an integer array, keeping first in place
(6 answers)
Closed 3 years ago.
I have an array which contains numeric values, these values range from 0 to 6. I would like to sort them in an "ascending" order, by specifying the starting number and ending number.
So let's say I want to start from 2, and end on 1..
These values would have to be sorted as such:
2, 3, 4, 5, 6, 0, 1
Or if I want them to start from 4, and end on 3..
These values would have to be sorted as such:
4, 5, 6, 0, 1, 2, 3
I may be overthinking this, but I'm not sure how to use the .sort() functionality for that, how and what would I have to compare against which values exactly?
const startFrom = 4;
const endAt = 3;
const arr = [0, 1, 2, 3, 4, 5, 6];
arr.sort((a, b) => {
// What should I compare to what here?
// .. and what do I return in which case?
});
Using sort,splice,push and unshift
const startFrom = 4;
const endAt = 3;
const arr = [0, 1, 2, 3, 4, 5, 6];
arr.sort(function(a,b){return a-b});
arr.splice(arr.indexOf(startFrom),1)
arr.splice(arr.indexOf(endAt),1)
arr.unshift(startFrom)
arr.push(endAt)
console.log(arr)

How can I convert an array of digits into an interger in Javascript

How can I convert an array of 6 integers into a single integer. Example provided below of what I want to do.
Array: {0, 1, 2, 3, 4, 5, 6}
Integer: 123456
Thank you!
Using join and Number
Read here first before using Number, Join, Array
let arr =[0, 1, 2, 3, 4, 5, 6];
let op = Number(arr.join(''))
console.log(op);
Simplest way would be:
const arr = [0, 1, 2, 3, 4, 5, 6];
const int = parseInt(arr.join(""), 10);
console.log(int)
From MDN Number page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number :
Number.parseInt() The value is the same as parseInt() of the global object.
Added radix argument, as #Bergi pointed out. Although in this case js engine will assume it is 10.
This logic takes a running total. Starting at zero, for every number, multiply the total by ten to shift it to the next higher order, and then add the integer.
var data = [0, 1, 2, 3, 4, 5, 6];
var result = data.reduce(function(total, integer){
return total * 10 + integer;
}, 0);
console.log(result);

Enumerable Functions Specifically the `.reduce()` function in JavaScript

I have this code here that I've set up:
var numbers = [1,2,3,4,5,6,7,8,9,2,3,4,5,6,1,2,3,4,5,6,7,8,8,4,3,2];
var greaterThan3 = numbers.filter (item => item >= 3);
console.log(greaterThan3);
greaterThan3.reduce((item, amount) => item + amount);
but it only gives me this:
[3, 4, 5, 6, 7, 8, 9, 3, 4, 5, 6, 3, 4, 5, 6, 7, 8, 8, 4, 3]
And, I know it probably has something to do with how I set up the .reduce() line. I'm trying to get the numbers greater than or equal to 3 to add up to one number. I'm assuming I have to define total and amount but I'm not sure. Just learning this chapter from Bloc so excuse the probably dumb question.

Categories