Longest Even word [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need to find the longest even word from a sentence.
I've tried this code for finding the largest word.
But I need the even word.
Can anyone please help me?
function FindlongestWord(input) {
var arrWords = input.split(' ');
var wordlength = 0;
var word = '';
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length) {
wordlength = wrd.length;
word = wrd;
}
});
return word;
}

Using modulus operator in the if statement
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length && wrd.length % 2 == 0) {
wordlength = wrd.length;
word = wrd;
}
});

function FindlongestWord(input) {
var arrWords = input.split(' ');
var wordlength = 0;
var word = '';
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length && !wrd.length%2) {
wordlength = wrd.length;
word = wrd;
}
});
return word;
}

Alternative solution.
const longestWord = (str) => str.split(' ').filter(v => !(v.length % 2))
.sort((a,b) => b.length - a.length)[0];
console.log(longestWord('hi there hello four longer longestt'));

Related

Create a function that takes a word and returns true if the word has two consecutive identical letters [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
// Create a function that takes a word and returns true if the word has two consecutive identical letters.
What am I doing wrong?
module.exports = (word) => {
for (let i = 0; i <= word.length; i++) {
for (let j = i + 1; j <= word.length; j++) {
if (word[j] == word[i]) {
return true;
}
} return false;
}
};
You can do this with only 1 loop.
function hasConsecutiveIdenticalLetters(word){
for (let i = 1; i < word.length; i++) {
if (word[i-1] === word[i]) {
return true;
}
}
return false;
}
You can also achieve this like below using some
const hasConsecutiveIdenticalLetters = (word: string) => (word).split('').some((letter, index) => letter === word[index + 1]);

find occurence of a character [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
find consecutive occurrences of 1
say i have an string
var str = "11101111110";
so my result would be
from 011111101111110
to 01111101011111010
can anyone help my generate a code that would get that result?
Simply replace it using regex
var str = "011111101111110";
str = str.replace(/(1{5})/g, '$10');
console.log(str);
var str = "011111101111110";
var count = 0;
for(var i = 0; i < str.length; i++){
if(count == 5){
str = str.substring(0,i) +"0"+str.substring(i);
}
if(str.charAt(i) == 1){
count++;
} else {
count = 0;
}
}
if(count == 5){
str = str + "0";
}
console.log(str);

Javascript word counter [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I wanted to make a basic word counter based on the amount of whitespaces in a sentence, but for some reason it doesn't work.
function countWords(str) {
if (typeof str == "string" && str.length > 0) {
var counter = 1;
for (var i; i < str.length; i++) {
if (str[i] === " ") {
counter += 1;
}
}
return counter;
} else {
throw Error("You must input a string.");
}
}
console.log(countWords("hello World"));
This throws 1 instead of 2.
You shouldn't use a loop for this. You would rather just split the string by space and take the resulting array's length
let countWords = str => str.split(' ').length;
console.log(countWords("foo bar"));
Initialize i to zero.
Replace for (var i; with for (var i=0;
You must initilize the counter inside the for, like var i = 0; here is your code
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
countWords("hello World");
Or you can count words with str.split(" ").length
Your for loop was wrong
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i = 0;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
var str = "hello World this is me";
console.log(countWords(str));

Delete identical elements from string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Got string, need to delete same words from there.
Here is my code. I tried to split string into array and then sort but it didn't work. It didn't even go through my if. I would like to hear your advice and maybe working code :)
var str = "I wont go anywhere as soon as I wont go there";
var array = str.split(" ");
document.getElementsByTagName('p')[0].innerHTML = str;
document.getElementsByTagName('p')[1].innerHTML = array;
document.getElementsByTagName('button')[0].onclick = function () {
for (var i = 0; i < array.length; i++) {
if (array[i] == array[i + 1]) {
array.splice(i, 1);
}
}
document.getElementsByTagName('p')[2].innerHTML = array;
}
If you like one-lines try this
var reducedString = array.reduce(function(out, s) {
return out.indexOf(s) == -1 ? out + ' ' + s : out;
},'').substring(1);
or in ES6
var reducedString = array.reduce( (out, s) => out.indexOf(s) == -1 ? out + ' ' + s : out);
Your problem is that you don't check every array element with every other array element.
Your code:
for (var i = 0; i < array.length; i++) {
if (array[i] == array[i + 1]) {
array.splice(i, 1);
}
}
Just checks array elements in sequence.
Try:
for (var i = 0; i < array.length; i++) {
for(var j = 0; j < array.length; j++){
if (array[i] == array[j] && i != j) {
array.splice(i, 1);
}
}
}
You can use an ES6 Set with the spread syntax after splitting the sentance:
const str = "I wont go anywhere as soon as I wont go there";
const unique = [...new Set(str.split(' '))].join(' ');
console.log(unique);
In ES5 you can use Array#reduce with a dictionary object.
var str = "I wont go anywhere as soon as I wont go there";
var dict = Object.create(null); // creates an empty object, without inherited properties and methods
var unique = str.split(' ').reduce(function(arr, w) {
if(!dict[w]) {
arr.push(w);
dict[w] = true;
}
return arr;
}, []).join(' ');
console.log(unique);
You can just replace the substring you are searching for
var ret = "data-123".replace('data-','');
console.log(ret);

Javascript: Broken letter shifting function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Trying to write a simple function to take a string as input, then shift each character over once alphabetically. (a -> b) (f -> g) (z -> a). My function so far is broken. I'm sure there are better ways to go about this, but if someone would be willing to troubleshoot my function that would be awesome. :)
function translate(str) {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k',
'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
str.toLowerCase();
var i = 0;
var j;
//edit: deleted str = ""
while (i < str.length) {
for (j = 0; j < alphabet.length; j++) {
if (str[i] == alphabet[alphabet.length - 1]) { //changed data type
str += alphabet[0]
j=0;
} else if (str[i] == alphabet[j]) {
str += alphabet[j+1]; //fixed this
j=0;
} else {
i++;
}
}
}
return str;
You could also use charCodeAt and fromCharCode to realize your shifting. I might be a little bit more convienent:
function translate(str) {
res = [];
for (var i = 0; i < str.length; i++) {
var ch = str.charCodeAt(i);
//65 => A
//90 => Z
//97 => a
//122 => z
//if ch betweet A and Z or between a and z
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) {
//if z or Z transform to a or A respectively
if (ch === 90 || ch === 122) ch -= 25;
//else increase by one
else ch += 1;
}
res.push(ch);
}
return = String.fromCharCode.apply(this, res);
}
Both methods use unicode representation of the string. Essentially, you transform the single characters into numbers, increase those numbers by one and transform it back to a letter. Here is a unicode table that shows the value of each letter: http://www.utf8-chartable.de/unicode-utf8-table.pl?utf8=dec
Your logic is a little flawed. Just iterate through the string and use the indexOf method along with the modulo operator:
var index = alphabet.indexOf(char.toLowerCase());
if (index === -1) {
// char isn't in the alphabet, so you should skip it
} else {
var newChar = alphabet[(index + 1) % alphabet.length];
}
(index + 1) adds 1 to the index, which selects the next letter, and % alphabet.length makes it wrap around to the beginning in case of z.
Here's one way to do it:
function translate(str) {
var newStr = "";
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
for (var i = 0; i < str.length; i++) {
var currentLetter = str.substring(i, i+1);
var newLetter = alphabet[(alphabet.indexOf(currentLetter.toLowerCase()) + 1) % alphabet.length];
// preserve the case of the letter
newStr += (currentLetter === currentLetter.toUpperCase()) ? newLetter.toUpperCase() : newLetter;
}
return newStr;
}
The general idea is to loop through each character, find its position in the alphabet array, and add its successor to the new string.
You'll have to add more logic if you need it to handle strings containing symbols, numbers, etc.
I can see a few problems here.
var str = "";. str is the variable you are sending as a parameter, so you reset it with this statement.
if (str[i] == alphabet.length - 1). str[i] and alphabet.length - 1 are not the same data type, so this statement is probably not doing what you think it should. Maybe you should have alphabet[alphabet.length - 1] instead.
else if (str[i] == alphabet[j]) { str += alphabet[j]; //... }. This would add the same letter onto your result string if you didn't reset str like in #1. You should have something like alphabet[(j+1) % alphabet.size] instead.
Also, you should use charAt(i) for getting characters in a string, not subscripts ([]), and you don't have to call j=0 at the end of your for loops, since you already say j=0 in the loop.

Categories