i just want to develop my thinking logic in pure js. The problem is that when i run the script in the console with the help node.js, it shows me for each iteration. Vowel and consonants. But i just need to write in console only once. Maybe, i should save result in a separate variable after the entire list of vowels? But i don't how to do, Below is the code:
// problem who i can't do
function letter(arg) {
var vowel = "aeouiAEOUI";
var result = "";
for(var i = 0; i < vowel.length; i++) {
if(arg === vowel[i]) {
console.log("vowel");
} else {
console.log("consonant");
}
}
}
i found resolved task on the Stack Overflow. But i don't understand why ? arg >= 0 ?
function letter_indexof(arg) {
var vowels = ["a","e","i","o","u"];
if(vowels.indexOf(arg.toLowerCase()) >= 0) {
console.log("vowel");
} else {
console.log("consonant");
}
}
i will be grateful to all for help.
To tweak your current code, you can have a variable which indicates whether the character is a consonant, and starts out as true, and if you find a vowel, reassign it to false, then check that variable:
function letter(arg) {
var vowel = "aeouiAEOUI";
var result = "";
let isConsonant = true;
for (var i = 0; i < vowel.length; i++) {
if (arg === vowel[i]) {
isConsonant = false;
}
}
if (isConsonant) {
console.log("consonant");
} else {
console.log("vowel");
}
}
letter('a');
letter('f');
You could also log and return immediately when finding a vowel:
function letter(arg) {
var vowel = "aeouiAEOUI";
var result = "";
for (var i = 0; i < vowel.length; i++) {
if (arg === vowel[i]) {
console.log("vowel");
return;
}
}
console.log("consonant");
}
letter('a');
letter('f');
It would be easier to use a regular expression, though:
const letter = arg => console.log(
/[aeiou]/i.test(arg) ? 'vowel' : 'consonant'
);
letter('a');
letter('f');
Related
im about to make a program that the output obtain the domain of the email. how to do that without built-in function such as .map .filter .reduce .split .join .indexOf .findIndex .substring
i do search and many answer said i have to use for loop, i can find the "#" and find the "." but how to make those string between "#" and "." to be an output
ex: input = mybest#gmail.com
output = gmail
input = triple2#yahoo.com
output = yahoo
let input = "mybest#gmail.com"
let output = ""
let begin = ""
let end = ""
for (let i = 12; i<input.length; i++){
if(input[i] == "#"){
begin += input[i+1]
}
}
for (let j = 0; j<input.length; j++){
if(input[j] == "."){
end += input[j-1]
}
}
function tmp() {
let input = "mybest#gmail.com"
let output = []
let didReachAt = false
for (let i = 0; i < input.length; i++) {
if(input[i] == "#") {
didReachAt = true
} else if(input[i] == '.'){
break
} else if(didReachAt) {
output.push(input[i])
}
}
return output.join('')
}
console.log(tmp())
The key here is to only start appending to the output when you come across an # and stop appending when you come across a . When you come across a ., you know you have your output so you can break and return the value.
let input = "mybest#gmail.com"
for (let i = 0;i<input.length;i++) {
if (input[i] === '#') {
var start = i+1
} else if (input[i] === '.') {
var end = i+1
return
}
}
let output = input.substring(start,end)
Simple solution although this does not account for errors such as a false input
So i can see that you started with javascript, so you can learn better using code like this.
var input = "triple2#yahoo.com"
var domainWithoutCom = input.split('#')[1].split('.')[0]
console.log(domainWithoutCom)
split can do the job for you!
EDIT:
Sorry about that, so i will create one version to you check my answer back :)
Check this, i think that can be improve, but can give you an idea :)
var email = 'calvin.nunes#yahoo.com';
var count = 0;
var domain = '';
var findFirst = false;
var searching = true;
do {
var char = email[count];
if (findFirst) {
if (char == '.') {
searching = false;
} else {
domain += char;
}
}
else {
if (char == '#') {
findFirst = true;
}
}
count += 1;
} while (searching == true);
console.log(domain)
I am trying to write a function that identifies if a word is an isogram or not. This is what I have done so far:
function isIsogram(word) {
var result;
var counter = 0;
var dubs = 0;
if (word.length === 0) {
result = false;
} else {
var lower = word.toLowerCase();
var array = Array.from(lower);
for (i = 0; i < array.length; i++) {
counter++;
for (j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) {
dubs++;
}
}
}
if ((counter > 0) && (dubs === 0)) {
result = true;
} else if ((counter > 0) && (dubs > 0)) {
result = false;
}
}
console.log(result);
return result;
}
isIsogram("word");
When I run the above code in my browser's javascript console, it works pretty well. But when I post it onto the environment where I am being tested, it gives an error that "word" (the parameter) is undefined.
I even tried hard coding a parameter by declaring a string value for word outside the function, it still said undefined. What am i not doing right?
Seems to work as far as I can see.
Can you provide information about how you call your function isIsogramm('teststring');?
https://jsfiddle.net/TobiObeck/z15eos81/
I'm writing a function that takes a string as an argument, checks it for a given character (say "B" in this case), and then returns an integer that reflects the number of times that character appeared. I'm aware that this can be done using regex and such, but the tutorial I'm using has so far made no mention of regex. Code time:
function countBs(string) {
var i = 0;
var n = 0;
var position = string.charAt(n);
while (i < string.length) {
if (string.charAt(n) == "B")
n += 1;
i++; //This line causes the following else statement to throw a syntax error. But it's the only way I can think of to have the loop continue iteration *while* checking for equivalence to "B"
else
i++;
return n;
}
}
And then check with console.log(countBs("ABBA"));
Your code is quite broken.
function countBs(string) {
var i = 0;
var n = 0;
// var position = string.charAt(n); // REMOVE--NOT NECESSARY
while (i < string.length) {
if (string.charAt(i) == "B") // i, NOT n
n++; // CONSISTENCY IN ADD-ONE SYNTAX
// i++; // INCREMENT ONCE BELOW
//else
i++;
}
return n; // MUST GO OUTSIDE THE LOOP
}
Correct code would therefore be:
function countBs(string) {
var i = 0;
var n = 0;
while (i < string.length) {
if (string.charAt(i) == "B") n++;
i++;
}
return n;
}
There's nothing particularly wrong with using a while loop, but a for would be more natural:
function countBs(str) {
var n = 0;
for (var i = 0; i < str.length; i++) if (str[i]== "B") n++;
return n;
}
Modern JS
For your reference, in modern JS, you could avoid the loops and variables. First, let's write a separate checking function:
function isB(c) { return c === 'B'; }
Then write
function countBs(str) {
return str . split('') . filter(isB) . length;
}
or, using reduce:
function countBs(str) {
return str.split('').reduce(function(cnt, c) {
return cnt + isB(c);
}, 0);
}
or, although you said you didn't want to use regexps:
function countBs(str) {
return (str.match(/B/g) || []) . length;
}
If you are writing in an ES6 environment, then using array comprehensions
function countBs(str) {
return [for (c of str) if (isB(c)) c] . length;
}
Try wrapping it in curly braces:
if (string.charAt(n) == "B")
{ n += 1;
i++;
}
An else requires a previous if, and no other statements in between. i++ was outside the if.
Here's my answer
function countBs(Str)
{
let char = "B" ;
return String(Str).split(char).length - 1;
}
function countChar(Str, char)
{
return String(Str).split(char).length - 1;
}
Can someone please tell me the best way to check if an object within an array of objects has a type of 11?
Below is what I have but it will alert for every object in the array, can I check the whole array and get it to alert just the once at the end?
I've seen methods like grep but I've been trying and can't get it to work. I'm using jQuery.
var x;
for (x = 0; x < objects.length; x++) {
if (objects[x].type == 11) {
alert("exists");
} else {
alert("doesnt exist");
}
}
Best way is use Array.some:
var exists = objects.some(function(el) { return el.type === 11 });
In the link there is also a shim for the browser that doesn't support it.
Otherwise you can just iterate:
var exists = false;
for (var i = 0, el; !exists && (el = objects[i++]);)
exists = el.type === 11;
Once you have the exists variable set, you can just do:
if (exists) {
// do something
}
Outside the loop, in both cases.
Your code should actually do it. If you're bothered that the loop will continue uselessly, you can abort it by calling break;
if(objects[x].type == 11){
alert("exists");
break;
}
Make it a function:
function hasObjWithType11(arr) {
var x;
for (x = 0; x < arr.length; x++) {
if(arr[x].type == 11){
return true;
}
}
return false;
}
alert(hasObjWithType11([{type:1}, {type:11}]); // alerts true
This will do it
var exists = false;
for (var x = 0; x < objects.length; x++) {
if(objects[x].type == 11){
exists = true;
break;
}
}
if(exists){
alert("exists");
}
You could make the searching code more reusable by wrapping it into a separate function. That way you can externalize the condition for easier reading:
function array_contains(a, fn)
{
for (i = 0, len = a.length; i < len; ++i) {
if (fn(a[i])) {
return true;
}
}
return false;
}
if (array_contains(objects, function(item) { return item.type == 11; })) {
alert('found');
}
You could also use Array.some():
if (objects.some(function(item) {
return item.type == 11;
})) {
alert('exists');
}
For IE < 9, refer to the MDN documentation for a mock version.
I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)