How to print out the even numbers in reverse order? - javascript

var num = prompt("Enter an integer : ");
var reversenum = num.reverse('');
document.write(reversenum);
I want to print out the even number of integers in reverse order after inputting an integer through the prompt, but I have no idea.
Even if I try to write split(), I don't think I can separate it because the letters are attached to each other. What should I do?
The result I want is,
Enter an integer : 8541236954
46248

Based on your updated question, I suppose what you want is to extract even-valued digits from a given integer, and display them in reverse order.
Since prompt() always returns a String, you can do one of the two ways to split it into digits and reverse their order:
Old-school JS way: num.split('').reverse()
ES6 array spread way: [...num].reverse()
Then, it is just a matter of using Array.prototype.filter() to return even numbers. Even numbers can be selected based on the criteria that their modulus of 2 is always 0 (i.e. when number is divided by 2, it has a remainder of 0).
Finally, join your filtered array so you get a string again.
See proof-of-concept order below:
const num = prompt("Enter an integer : "); // e.g. try '8541236954'
const digits = [...num].reverse();
const evenDigits = digits.filter(d => d % 2 ===0);
console.log(evenDigits.join('')); // e.g. '46248'

You need to first split the string into an array of characters, reverse the array and then join it again. I have given an easy to understand code which converts every character of the reversed string to an int and checks if that integer is even, followed by concatenating it in the answer.
var num = prompt("Enter an integer : ");
var reversenum = num.split('').reverse().join('');
var ans = "";
for (var i = 0; i < reversenum.length; i++)
{
var x = parseInt(reversenum[i]);
if(x%2 === 0)
ans = ans.concat(reversenum[i]);
}
console.log(ans);

Related

Get String Specific Characters

I am trying to write some code that takes a uuid string and returns only the characters between the 2nd and 3rd _ characters in an array. What I currently have below is returning every character in the string in to the array. I have been looking at this for some time and am obviously missing something glaringly obvious I suppose. Can someone maybe point out what is wrong here?
var uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
var count = 0
var values = []
for(y=0; y<uuid.length; y++){
if(uuid.charAt(y) == '_'){
count++
}
if(count = 2){
values.push(uuid.charAt(y))
}
}
return values
EDIT:
So for my case I would want the values array to contain all of the characters in 5be0lk875iou
You can get the same behavior in less lines of code, like this:
let uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
let values = uuid.split("_")[2];
You can use the split function to do that:
let values = uuid.split("_");
By using the split function, you can get separate the whole string into smaller parts:
const parts = uuid.split("_");
This will return the following array:
["159as", "ss", "5be0lk875iou", ".1345.332.11.2"]
From here, you can take the string at index 2, and split it again to receive an array of characters:
const values = parts[2].split("");

Javascript: How cut out part of an integer?

How to cut out part of an integer?
What can i do to get an integer 12 or 123 from a variable n
let n = 123456;
A simple way to do this would be to just cast the input number to a string, and then take a substring:
var n = 123456;
n = n + "";
var output = n.slice(0, 2);
console.log(output);
Another approach, if all you want is to get some number of leading digits, would be to divide by the correct multiple of ten, e.g.
var n = 123456;
var output = Math.floor(output / 10000);
The strategy I suggest is to convert the integer value to a string which you may manipulate with parseInt() as well as the string's substr() method, as follows:
const START = 0;
const first_two = 2;
const first_three = 3;
const base_ten = 10;
let n = 123456;
let res = parseInt( String( n ).substr( START,first_two ),base_ten );
console.log(res);
res = parseInt(String( n ).substr( START,first_three ),base_ten );
console.log(res);
The Number Object has a toString() method but apparently it is safer to convert the integer to a string by passing the integer value of n to the String Object per this discussion. You may then use the String Object's substr() method to access the first two or three digits appearing in the string. Next, you may take the resulting numeric string and pass it to parseInt(), along with a base parameter to obtain the integer value.
I think this will work for you - you first change it to string and split it to an array and then remove the unwanted characters, then join the array together, and parse it as an integer: (edited to reflect #VLAZ's comment.
parseInt(n.toString().slice(0,2)));

How can I sum all numbers 1 from a string?

I need to sum all numbers 1 from a string!
For example: "00110010" = 1+1+1 = 3...
psum will receive this result and then I will check
if(psum >= 3){
return person;
}
I need to find a way to solve it in javascript ES6 but I can't use any for, while or forEach loop, unfortunately!!!
Could you help me?
You need to use the reduce() method.
let input = '00110010'
let array = input.split("").map(x => parseInt(x));
let sum = array.reduce((acc, val) => {
return acc + val;
});
console.log(sum)
In one statement:
let psum = "00110010".split('').reduce((t, n) => {return t + parseInt(n)}, 0);
console.log(psum);
Note that summing the numbers 1 comes down to counting the numbers 1, which is what the following solutions do in different ways:
With match
You could use a regular expression /1/g:
var p = "00110010";
var psum = (p.match(/1/g) || []).length;
console.log(psum);
match returns an array of substrings that match with the pattern 1. The / just delimit this regular expression, and the g means that all matches should be retrieved (global). The length of the returned array thus corresponds to the number of 1s in the input. If there are no matches at all, then match will return null, so that does not have a .length property. To take care of that || [] will check for that null (which is falsy in a boolean expression) and so [] will be taken instead of null.
With replace
This is a similar principle, but by matching non-1 characters and removing them:
var p = "00110010";
var psum = p.replace(/[^1]/g, "").length;
console.log(psum);
[^1] means: a character that is not 1. replace will replace all matches with the second argument (empty string), which comes down to returning all characters that do not match. This is like a double negative: return characters that do not match with not 1. So you get only the 1s :-) .length will count those.
With split:
var p = "00110010";
var psum = p.split("1").length - 1;
console.log(psum);
split splits the string into an array of substrings that do not have the given substring ("1"). So even if there are no "1" at all, you get one such substring (the whole string). This means that by getting the length, we should reduce it by 1 to get the number of 1s.
With a recursive function:
var p = "00110010";
var count1 = p => p.length && ((p[0] == "1") + count1(p.slice(1)));
var psum = count1(p);
console.log(psum);
Here the function count1 is introduced. It first checks if the given string p is empty. If so, length is zero, and that is returned. If not empty, the first character is compared with 1. This can be false or true. This result is converted to 0 or 1 respectively and added to a recursive call result. That recursive call counts the number 1s in the rest of the input (excluding the first character in which the 1s were already counted).

Trim long number in JavaScript

For example, I got that long nubmer 1517778188788. How can i get first 6 digits from that number, like 151777 and trim another digits?
Just convert a number to string and then slice it and convert it back to Number.
const a = 1517778188788;
const str_a = a.toString();
const result = Number(str_a.slice(0, 6));
new String(your_number).substring(0,6)
(basically converting it to a string and substringing it). Don't forget to parse it back afterwards
Applicable only when you want to strip last 7 digits, and the numbers have constant length (13 in this case). Still leaving you with first 6 ones though.
const nr = 1517778188788;
const result = Math.floor(nr / 10000000)
Try this:
var num = 1517778188788; // long number
var str = num.toString(); //convert number to string
var result = str.substring(0,6) // cut six first character
result = parseInt(result); // convert it to a number
here is a working fiddle

Adding numbers within a string

I want to take a string of numbers and characters and add up the numbers.
For example: "In 2015, I want to know how much does iPhone 6+ cost?"
Output: 2021
Here is my current code:
var str = "In 2015, I want to know how much does iPhone 6+ cost?";
function sumFromString(str){
var punctuationless = str.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var StringList = finalString.split(" ");
var sum = [];
for (i = 0; i < StringList.length; i++)
if (isInt(StringList[i])
sum.add(StringList[i]);
sum.reduce( (prev, curr) => prev + curr );
}
sumFromString(str);
My code takes a string and strips it of punctuation and then places each individual word/number into the array, StringList.
I can't get the next part to work.
What I tried was to iterate through each value in the array. The if statement is supposed to check if the array element is an integer. If so, it will add the integer to an empty array called sum. I then add all the values of the array, sum, together.
Much simpler:
function sumFromString(str) {
return (str.match(/\d+/g)||[]).reduce((p,c)=>+c+p);
}
Note in particular that I use +c+p - +c casting the current value from a string to a number, then adding it to p. This matches all the numbers in the string - getting an empty array if there were none - and reduces that.
For the sake of variety, here's a way to do it without regular expressions:
var myString = "5 bunnies ate 6 carrots in 2days.";
var myArray = myString.split('');
var total = 0;
for (var i = 0; i < myArray.length; i++) {
if (!isNaN(parseInt(myArray[i]))) {
total += parseInt(myArray[i]);
}
}
Fiddle Demo
note: If there's a chance myString could be null, you'd want to add a check before the split.
Split the string into an array of all characters with the split function and then run the filter function to get all numbers. Use the map function to go through all elements that include numbers, and delete characters from them that aren't digits.
Then use reduce to get the sum of all numbers. Since we're dealing with strings here, we have to perform type conversion to turn them into numbers.
string.split(' ').filter(function(word) {
return /\d+/.test(word) }
}).map(function(s) {
return s.replace(/\D/, '')
}).reduce(function(a,b) {
return Number(a) + Number(b);
});

Categories

Resources