could you please help me understand why the following line result is [1,3]?
[1,3,6].filter( item => item % 2)
I was expecting to receive the even number from the array.
Many thanks!
Filter checks for a boolean, 3 % 2 is equal to 1, which evaluates to true.
You want item % 2 == 0
Even numbers are those numbers that are exactly divisible by 2.
The remainder operator % gives the remainder when used with a number. For example,
const number = 6;
const result = number % 4; // 2
Hence, when % is used with 2, the number is even if the remainder is zero. Otherwise, the number is odd.
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
//check if the number is **even**
if(number % 2 == 0) {
console.log("The number is even.");
}
// if the number is **odd**
else {
console.log("The number is odd.");
}
ref : https://www.programiz.com/javascript/examples/even-odd
Related
How to verify if an input type number contains a maximum of 3 decimals, without using regex?
let x = 1.5555
let y = 1.55
x is false
y is true
You can use a formula like:
(x * 10**N) % 1 === 0
Here x is your number that potentially contains decimals (eg: 1.555) and N is the maximum amount of decimal places you want to allow for.
Eg, for numbers with 3 (N = 3) or fewer decimal places, you will get x*1000, which will evaluate to an integer. Eg:
1.55 -> 1550
1.555 -> 1555
For numbers with more than 3 decimal places, doing x*1000 won't convert it to an int, it will only shift parts of the number over:
1.5555 -> 1555.5 // still a decimal
The % 1 check then gets the remainder of the above number if it was to be divided by 1. If the remainder is 0, then the number was converted to an integer, if it is more than 0, then x*1000 failed to convert the number to an int, meaning that it has more than 3 decimals:
const validate = (x, N) => (x * 10**N) % 1 === 0;
console.log(validate(1.5555, 3)); // false
console.log(validate(1.55, 3)); // true
console.log(validate(1.555, 3)); // true
console.log(validate(0.00000001, 3)); // false
You can convert to string using the toString() method, then split at the point . with the .split() method this will result in an array.
The first element in the array is a string containing the whole number part which is not interesting here for us.
The second element at indice 1 in the resulting array is the decimal part as string.
Now you can check the length property of this string if it is equal or less then three which means it has three or less decimal numbers then we return true in the validation function when not we return false.
const x = 1.5555;
const y = 1.555;
const z = 1.55
function validate(num){
return num.toString().split(".")[1].length <= 3;
}
console.log(validate(x));
console.log(validate(y));
console.log(validate(z));
This may solve your problem
let x = 1.5555;
let y = 1.55;
int length = x.Substring(number.IndexOf(".")).Length;
bool result = length > 3 ? true: false;
I'm looking to answer the question, but most important to understand where I did it wrong and why. In a certain way to learn how to do it.
So, the question is:
We've already declared a variable for you in the editor called number to which the value 42 was assigned.
Use a for loop to go through all numbers from number up to 50 (both inclusive), and check if they are multiples of 3. If they are, print them.
And I got to a point that I print to the console and I get the answer I want: 42, 45, 48.
But the console still gives me an error:
Remember the remainder operator? It might be of help to check if a number is a multiple of 3.
This is my code:
var number = 42;
var dividedbyThree = [];
for (var number = 42; number <= 50; number++) {
if (number % 3 == dividedbyThree) {
console.log(number);
}
}
What am I doing wrong?
Just replace
if (number % 3 == dividedbyThree)
with
if (number % 3 === 0)
DEMO:
var number = 42;
for (var number = 42; number <= 50; number++) {
if (number % 3 === 0) {
console.log(number);
}
}
The code will look like this
var number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
console.log(number); }
}
The number which returns 0 as the remainder when it is divisible by 3. So we check the remainder is equal to 0. if this condition satisfied console.log will print the number which is divisible by 3. if you need to push the numbers into new array, your code will look like this
var divBy3=[],number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
divBy3.push(number)
}
console.log(divBy3)
}
<script>
function calculate() {
var num = document.getElementById("decimal").value; //fetching binary value from html input box.
var bin = [];
while (num > 0) {
bin[bin.length] = num % 2;
num >>= 1; // basically /= 2 without remainder if any
}
document.getElementById("result").innerHTML = "Binary Value: " + bin.reverse().join('');
}
</script>
I am trying to understand this code i can't understand these two lines in this code:
bin[bin.length] = num % 2;
num >>= 1;`
bin[bin.length] = num % 2;
Append a 0 or 1 to bin depending on whether num is even or odd.
num >>= 1;
As the comment says, this divides num by 2 without remainder. Overall, the loop puts the digits of the binary representation of num into bin from least significant to most. That is why it is reversed at the end.
bin[bin.length] is just the index of the number (string,actually) that will be crated. For each bin.reverse() it increments by one. The num is a number in digital form. num >>= 1 just shifts right 1 digits. This has an affect to divine the decimal by 2. bin[bin.length] = num % 2 just result to 0 or 1 and add each time to the string to form the final answer.
I am not sure which part you do not understand. Some operator or the whole logic?
You want to know how bin[bin.length] = ... puts the value in the correct spot. Well, bin starts as an empty array (bin = []) which has length 0. So bin[bin.length] = bin[0] to start and the first thing is inserted appropriately at index 0.
This length property is maintained internally as things are inserted into the array. So it will always insert in the first available slot.
Example: after something has been added at index 0, the length property is updated to 1 and the next insertion is done at bin[bin.length] which is equivalent to bin[1].
So I have a number like 5467. I want my code to return 546.
I tried taking the last number and subtracting it from the original number but I get 5460 instead of 546.
Combine / with %:
(5467 - (5467 % 10)) / 10
564
Sounds like you also need to divide my 10. You could do something like this:
var number = 5467;
number = number - (number % 10); // This will subtract off the last digit.
number = number / 10;
console.log(number); // 546
We first use the modulo operator % to get the last digit, and we subtract it from number. That reduces the number from 5467 to 5460. Now to chop off the last digit (which is guaranteed to be a 0) we divide by 10 and get 546.
Written more concisely you could do:
number = (number - ( number % 10)) / 10;
There's a few things you can do the most concise being:
Math.floor(num / 10);
Or, convert to a string, remove the last character and convert back to number.
parseInt(num.toString().slice(0, -1));
If string representation would be fine for you then one other way is
var num = 5467,
cut = (num/10).toFixed(); // <-'547'
Well... warning..! i have to say toFixed() method rounds if necessary. So in this particular example it doesn't work.
I dont mind some of the other answers, but i feel that this maybe too fixed on it being a number.
Which it is, but you want to remove the last digit/char, regardless of the number, so why not substr?
http://www.w3schools.com/jsref/jsref_substr.asp
var s = 5467;
s = s.toString().substr(0, s.toString().length - 1);
console.log(s)
or even easier:
var s = (5467).toString();
s = s.substr(0, s.length - 1);
console.log(s)
These dont take into account single digit numbers, so passing in 1 would return blank. To answer that you could simply do a check like:
var s = (1).toString();
if(s.length > 1)
s = s.substr(0, s.length - 1);
console.log(s)
Also, similar question to:
Remove last digits from an int
Remove the last digits of a number (not string)
Removing the last digits in string
To truncate digits from the right hand side until the number is less than 30, keep dividing by 10 and rounding down until a suitable value is reached:
var n = 12341235;
while (n > 30) n = n/10|0;
document.write(n);
The greater than and division operations will coerce n to a number, so it can be a number or string. If ToNumber(n) results in NaN (e.g. n = 'foo'), then the value of n is not modified.
You can simply divide the number by 10 and parseInt()
var num = 5467;
num = parseInt(num/10);
Update :
To repeat the process until the answer is less than 30, use while loop as
var num = 5467;
while(num >= 30) {
num = parseInt(num/10);
}
document.write(num);
I understand the basic concept of modulo: It give you the remainder with division. I don't seem to be able to grasp how to use it correctly in practice. For instance, the following code takes a number and if it divides evenly by 2 it will return true, otherwise it returns false:
if(number % 2){
return false;
}
else{
return true;
}
It seems to me intuitively (and wrongly) that the way you would code it would be to set it so the modulo works out to 0:
if (number/2 %0) {
return true
Can anyone explain how and why the first one is correct? Keep in mind that I am obviously extremely dense ...
To check if a number divides without leaving a remainder you need to check if the result of the modulo devision is equal to zero.
if ((number % 2) == 0){
return true; // number was even
} else {
return false; // number was odd
}
From mdn % remainder documentation:
The remainder operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the integer remainder of dividing var1 by var2.
Taking that in mind, here are the results of using % with a few values:
59 % 2
> 1
60 % 2
> 0
0 is a falsey value in javascript, so the the result of 60 %2 is never going to pass your if test. To make a proper comparison you'll need to directly check if you have a value of 0:
if (number % 2 === 0)
return true
When you use the modulo (%) operator, you are basically saying:
number % x:
Divide number by x. Round the result down to nearest integer. Multiply that integer by x. Give me the distance (absolute value) of this number to the original number.
This might not be the exact mathematical definition of modulo, but I would like to believe it is pretty close for our needs.
To give a few examples...
2 % 2 = 0 (2 / 2 = 1, 1 * 2 = 2, abs(2 - 2) = 0)
3 % 2 = 1 (3 / 2 ≐ 1, 1 * 2 = 2, abs(2 - 3) = 1)
4 % 2 = 0 (4 / 2 = 2, 2 * 2 = 4, abs(4 - 4) = 0)
The problem with your notation is that it is one extra operation that needs to be performed by the programmer. Since the current way we express the modulo operation is quite concise and does not require us to do any divisions ourselves, there is potential for performance optimisations to be done under the hood.
To express what I believe is your intent, you basically calculate the modulo with the current syntax and compare it to a particular value:
if (number % 2 === 0)
return true // Yup, its divisible by 2
Building on top of the other answers, I'd like to mention that using an if / else to explicitly return a boolean value, when you've already evaluated a boolean value, is overly verbose.
If all you are doing in the if / else is returning a boolean on either side, then your return expression can be reduced.
Good:
function isEven(num) {
return (num % 2 === 0);
}
function isOdd(num) {
return (num % 2 !== 0);
}
Bad:
function badIsEven(num) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}