How to remove a specific letter from a string - javascript

Add a removeLetter function that takes a string and a letter. The result of the function should be string, which does not have the specified character in letter.
How to do peple?
function deleteLetter(string, letter) {
let final = '';
for (let i = 0; i<string.length; i++) {
if (string[i] === letter) {
final.concat(string[i])
}
return final;
}
}

You should return the result at the end of the function, not in the for loop
function deleteLetter(string, letter) {
let final = ""
for (let i = 0; i < string.length; i++) {
if (string[i] !== letter) {
final += string[i]
}
}
return final
}
console.log(deleteLetter("asdasd", "a"))

With ES2021 you'll be able to use String.replaceAll (already available on firefox stable (79) and chrome beta(85)/canary(86))
console.log("test".replaceAll("t", ""))

You can just use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
let str = 'test'
let replaced = str.replace('e', '')
console.log(replaced) // tst
But remember that only first occurrence will be replaced when u use string as first parameter. Use regex solution when you want to remove all of the letters

const removeLetter = (str, letter) =>
str.split('').filter(n => !n.includes(letter)).join('');
console.log(removeLetter('asd', 'a'));
or
const removeLetter = (str, letter) => str.replace(/[^letter]/, '');
console.log(removeLetter('asd', 'a'));

using splice & indexOf
function delLetter(word,letter){
let wordArr = word.split('');
let idx = wordArr.indexOf(letter);
wordArr.splice(idx,1); // deleted here
return wordArr.join('');
}
console.log(delLetter('twinkle','w'))

Related

how can i count chars from word which in the array?

i have an array ["academy"] and i need count chars from the string in the array.
output:
a:2
c:1
d:1
e:1
m:1
y:1
like this
i tried two for loops
function sumChar(arr){
let alph="abcdefghijklmnopqrstuvxyz";
let count=0;
for (const iterator of arr) {
for(let i=0; i<alph.length; i++){
if(iterator.charAt(i)==alph[i]){
count++;
console.log(`${iterator[i]} : ${count}`);
count=0;
}
}
}
}
console.log(sumChar(["abdulloh"]));
it works wrong
Output:
a : 1
b : 1
h : 1
undefined
Here's a concise method. [...new Set(word.split(''))] creates an array of letters omitting any duplicates. .map takes each letter from that array and runs it through the length checker. ({ [m]: word.split(m).length - 1 }) sets the letter as the object key and the word.split(m).length - 1is a quick way to determine how many times that letter shows up.
const countLetters = word => (
[...new Set(word.split(''))].map(m => ({
[m]: word.split(m).length - 1
})))
console.log(countLetters("academy"))
You can check the occurrences using regex also. in this i made a method which checks for the character in the string. Hope it helps.
word: string = 'abcdefghijklkmnopqrstuvwxyzgg';
charsArrayWithCount = {};
CheckWordCount(): void {
for(var i = 0;i < this.word.length; i++){
if(this.charsArrayWithCount[this.word[i]] === undefined){
this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);
}
}
console.log(this.charsArrayWithCount);
}
charCount(string, char) {
let expression = new RegExp(char, "g");
return string.match(expression).length;
}
You can simply achieve this requirement with the help of Array.reduce() method.
Live Demo :
const arr = ["academy"];
const res = arr.map(word => {
return word.split('').reduce((obj, cur) => {
obj[cur] = obj[cur] ? obj[cur] + 1 : 1
return obj;
}, {});
});
console.log(res);
I think this is the simplest:
const input = 'academy';
const res = {};
input.split('').forEach(a => res[a] = (res[a] ?? 0) + 1);
console.log(res);

I have a array of string have to find all the common character present from all strings

I have a array of string.
let arr=["robin","rohit","roy"];
Need to find all the common character present in all the strings in array.
Output Eg: r,o
I have tried to create a function for above case with multiple loops but i want to know what should be the efficient way to achive it.
Here's a functional solution which will work with an array of any iterable value (not just strings), and uses object identity comparison for value equality:
function findCommon (iterA, iterB) {
const common = new Set();
const uniqueB = new Set(iterB);
for (const value of iterA) if (uniqueB.has(value)) common.add(value);
return common;
}
function findAllCommon (arrayOfIter) {
if (arrayOfIter.length === 0) return [];
let common = new Set(arrayOfIter[0]);
for (let i = 1; i < arrayOfIter.length; i += 1) {
common = findCommon(common, arrayOfIter[i]);
}
return [...common];
}
const arr = ['robin', 'rohit', 'roy'];
const result = findAllCommon(arr);
console.log(result);
const arr = ["roooooobin","rohit","roy"];
const commonChars = (arr) => {
const charsCount = arr.reduce((sum, word) => {
const wordChars = word.split('').reduce((ws, c) => {
ws[c] = 1;
return ws;
}, {});
Object.keys(wordChars).forEach((c) => {
sum[c] = (sum[c] || 0) + 1;
});
return sum;
}, {});
return Object.keys(charsCount).filter(key => charsCount[key] === arr.length);
}
console.log(commonChars(arr));
Okay, the idea is to count the amount of times each letter occurs but only counting 1 letter per string
let arr=["robin","rohit","roy"];
function commonLetter(array){
var count={} //object used for counting letters total
for(let i=0;i<array.length;i++){
//looping through the array
const cache={} //same letters only counted once here
for(let j=0;j<array[i].length;j++){
//looping through the string
let letter=array[i][j]
if(cache[letter]!==true){
//if letter not yet counted in this string
cache[letter]=true //well now it is counted in this string
count[letter]=(count[letter]||0)+1
//I don't say count[letter]++ because count[letter] may not be defined yet, hence (count[letter]||0)
}
}
}
return Object.keys(count)
.filter(letter=>count[letter]===array.length)
.join(',')
}
//usage
console.log(commonLetter(arr))
No matter which way you choose, you will still need to count all characters, you cannot get around O(n*2) as far as I know.
arr=["robin","rohit","roy"];
let commonChars = sumCommonCharacters(arr);
function sumCommonCharacters(arr) {
data = {};
for(let i = 0; i < arr.length; i++) {
for(let char in arr[i]) {
let key = arr[i][char];
data[key] = (data[key] != null) ? data[key]+1 : 1;
}
}
return data;
}
console.log(commonChars);
Here is a 1 liner if anyone interested
new Set(arr.map(d => [...d]).flat(Infinity).reduce((ac,d) => {(new RegExp(`(?:.*${d}.*){${arr.length}}`)).test(arr) && ac.push(d); return ac},[])) //{r,o}
You can use an object to check for the occurrences of each character. loop on the words in the array, then loop on the chars of each word.
let arr = ["robin","rohit","roy"];
const restWords = arr.slice(1);
const result = arr[0].split('').filter(char =>
restWords.every(word => word.includes(char)))
const uniqueChars = Array.from(new Set(result));
console.log(uniqueChars);

How to join strings in a for loop in Javascript?

I am trying to capitalise the first character of each word and join all words into one string. I have managed to capitalise the first character of each word but cant seem to get .join() to work on the final result
function generateHashtag (str) {
let split = str.split(' ')
for(let i = 0; i < split.length; i++){
let finalResult = split[i].charAt(0).toUpperCase() + split[i].substring(1)
console.log(finalResult.join(''))
}
}
console.log(generateHashtag('Hello my name is')) should return ('HelloMyNameIs')
Achieving this by split is possible. first create an array of divided strings (by the delimiter ' ') and then loop around the array and capitalize the first char using the method toUpperCase and concat the rest of the string without the first letter using slice
function generateHashtag(str) {
let split = str.split(' ');
for (let i = 0; i < split.length; i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}
return split.join('');
}
console.log(generateHashtag('Hello my name is'));
More about split - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
you can do split[i] = split[i].charAt(0).toUpperCase() + split[i].substring(1) in the loop then outside loop do split.join('')
Basically you are replacing each word (split[i]) with capitalised word. Then in the end join the words.
finalResult is a String, not an Array so there is no join function.
Use this instead :
function generateHashtag (str) {
let arrayWords = str.split(' ')
const titleCasedArray = arrayWords.map(word => titleCaseWord(word))
return titleCasedArray.join('');
}
function titleCaseWord (word){
return word.slice(0,1).toUpperCase() + word.slice(1,-1).toLowerCase()
}
You can do something like this:
function generateHashtag (str) {
//returns array of strings
let split = str.split(' ')
//returns array of strings with each word capitalized
const capitalizedWordsArr = split.map( word => word.charAt(0).toUpperCase() + word.substring(1))
//returns a string by joining above array with no spaces
return capitalizedWordsArr.join('')
}
This is a perfect use-case for Array.prototype.reduce:
function generateHashtag(str) {
return str
.split(' ')
.reduce((acc, [firstLetter, ...rest]) => acc += `${firstLetter.toUpperCase()}${rest.join('')}`,
''
);
}
console.log(generateHashtag('Hello my name is')); // should return ('HelloMyNameIs')
Javascript strings are immutable so you cannot overwrite them on the go, but you can overwrite array elements.
By using String.prototype.substr() you can extract a part of the string, you can use these parts, modify it and create a new string then replace the old array element. finally returning the joined string like you wanted to
function generateHashtag(str) {
const split = str.split(' ') // array of words
for (let i = 0; i < split.length; i++)
split[i] = split[i].substr(0, 1).toUpperCase() + split[i].substr(1); // overwriting existing elements with Titlecased words
return split.join(''); // returning final string
}
console.log(generateHashtag('Hello my name is'))
You don't need to use join at all, just declare and initialize finalResult outside the loop and concatenate each word inside the loop:
function generateHashtag(str) {
const split = str.split(' '); // Array<String>
let finalResult = ''; // String
for(let i = 0; i < split.length; i++) {
const titleCased = split[i].charAt(0).toUpperCase() + split[i].substring(1);
finalResult += titleCased;
}
return finalResult;
}
console.log(generateHashtag('Hello my name is'));
However, you can simplify this code considerably by using a functional-programming (FP) style with map and reduce. See below.
I've also changed your code to use toLocaleUpperCase instead of toUpperCase and uses [0] for brevity.
It's still safe to use substring(1) for single-character strings, it just returns ''.
function generateHashtag(str) {
return ( str
.split(' ')
.map( word => word[0].toLocaleUpperCase() + word.substring(1).toLocaleLowerCase() )
.reduce( ( word, concat ) => concat + word, "" )
);
}
I forgot that join() can still be used instead of reduce (and will have an optimized implementation inside the JS engine anyway):
I've also moved the map function's logic to a named function toTitleCase.
function generateHashtag(str) {
const toTitleCase( word ) => word[0].toLocaleUpperCase() + word.substring(1).toLocaleLowerCase();
return ( str
.split(' ')
.map( word => toTitleCase( word ) ) // or just `.map( toTitleCase )`
.join()
);
}
The return statement has parens to prevent unwanted automatic-semicolon-insertion which would otherwise break the function.
If you want something similar to your code, but working, i would do this:
function generateHashtag (str) {
let split = str.split(' ')
let newStr = []
for (let i = 0; i < split.length; i++){
newStr.push(split[i].charAt(0).toUpperCase() + split[i].substring(1))
}
return newStr.join('')
}
You could also choose to do this task using a 'regular expression'.
https://cheatography.com/davechild/cheat-sheets/regular-expressions/
Here is a quick implementation:
const generateHashtag = str => {
// regular expression to capitalize the words
const regEx = /(\b[a-z](?!\s))/g
str = str.replace(regEx, (char) => {
return char.toUpperCase()
});
// remove spaces, return
return str.split(' ').join('')
}
Same code, but with less readability:
const generateHashtag = str => {
return str.replace(/(\b[a-z](?!\s))/g, (char) => {
return char.toUpperCase()
}).split(' ').join('');
}
function generateHashtag (str) {
return str.replace(/\b\S/g, e => e.toUpperCase()).replace(/\s/g,'');
}
console.log(generateHashtag('Hello my name is'))
\b: bondary \S: non space \s: space.
https://regex101.com/
//try this code solve your problem
const generateHashtag = str => {
let split = str.split(' ')
let finalResult = []
for (word of split) {
finalResult.push(word[0].toUpperCase() + word.substring(1))
}
return finalResult.join('')
}
console.log(generateHashtag('Hello my name is'))

How to flip every character with the character next to it. Javascript

Need help inside the for loop to flip each character with the character before it.
function flip(str) {
//split string
//iterate through split string
//return joined string
var splitt = str.split('');
for(var i = 0; i < splitt.length; i++){
//flip every character with one before it
}
}
var output = flip('otatl');
console.log(output); // -> 'total'
function split(str) {
let splitt = str.split('');
for (let i=0; i<splitt.length-1; i+=2) {
const temp = splitt[i];
splitt[i] = splitt[i+1];
splitt[i+1] = temp;
}
return splitt.join('');
}
You can use ES6 destructuring assignment.
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=0; i < splitt.length; i++){
//flip every character with one before it
if (i%2 == 1) {
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
You can combine this technique with gillyb's loop pattern to reduce the iterations as follows:
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=1; i < splitt.length; i+=2){
//flip every character with one before it
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
Can do something similar with regex and array manipulation
const flip = (stringToFlip) => stringToFlip
.split(/(.{2})/) // array of strings of 2 chars
.map((e) => e.split('') // convert each string piece to array
.reverse() // reverse array
.join('') // convert array piece back to string
)
.join(''); // combine all parts
const result = flip('otatl');
console.log("flip('otatl')");
console.log(result);
If we're not restricted to for loops, this is my (slightly too code golf-ish?) answer:
const flip = (str) =>
str
.split('')
.reduce((a, v, i) => (a[i + ((i % 2) * -2 + 1)] = v, a), [])
.join('');
console.log(flip('otatl'));
console.log(flip('lfpi'));
I'm sorry I am late to the party but you can use reduce().
let input = "vanjskojfdghpja";
let output = input
.split('')
.reduce(([o,p],c,i) => i%2?[o+c+p,'']:[o,c],['',''])
.join('');
console.log(output);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Determine groups in a string

I am trying to determine groups in a string.
For example "AAABBCCCCD" should have ["AAA", "BB", "CCCC", "D"] as groups based on the pattern in the string.
Here is my simple function to do that:
const patternGroup = (str) => {
let cursor = str[0]
let groups = []
let currentGroup = ""
for (let i = 0; i < str.length; i++) {
let ch = str[i]
if (ch === cursor) {
currentGroup += ch
}
else {
groups.push(currentGroup)
currentGroup = ch
cursor = ch
}
}
if (currentGroup !== "") {
groups.push(currentGroup)
}
return groups
}
It works as intented but I am looking for a simpler function, maybe using map/reduce or regex. Any ideas?
you can simply use RegExp:
var input = "AAABBCCCCD";
const res = input.match(/([^])(\1*)/g);
console.log(res)
Similar to your implementation:
const patternGroupWithReduce = (str) => {
let currentGroup = ""
return str.split("").reduce((acc, cur, i) => {
currentGroup += cur
if (str[i + 1] !== cur) {
acc.push(currentGroup)
currentGroup = ""
}
return acc
}, [])
}
const patternGroupWithRegex = (str) => {
return str.match(/(.)\1*/g)
}
RegEx /(.)\1/g* uses the back reference for the capturing group.
\1* matches the same char as recently captured one as many times as possible.
Here is the visualization for it:
You could use
(.)\1*
As in:
let string = "AAABBCCCCD";
let rx = /(.)\1*/g;
let parts = string.match(rx);
console.log(parts);
See a demo for the expression on regex101.com.

Categories