How to search for letters in words using javascript? - javascript

Let's say i have the letters a,b,s,d (say)
I have 100s of words in an array.
I want to use js to search for a word containing all the letters, and only if all letters are met, then return that word.
How do i do it?

OK, so here's an expanded version of the code originally posted by user4703663. I wanted to wait until they had a chance to undelete their answer but they never did.
var words = ['absd', 'dfsd', 'dsfefe', 'dfdddr', 'dfsgbbgah', 'dfggr'];
var str = 'absd';
function find(words, str) {
// split the string into an array
str = str.split('');
// `filter` returns an array of array elements according
// to the specification in the callback when a new word
// is passed to it
return words.filter(function(word) {
// that callback says to take every element
// in the `str` array and see if it appears anywhere
// in the word. If it does, it's a match, and
// `filter` adds that word to the output array
return str.every(function(char) {
return word.includes(char);
});
});
}
const output = find(words, str); // [ "absd", "dfsgbbgah" ]
console.log(output);

Related

Shorter more efficient way to tackle this codewars challenge?

I'm fairly new to JavaScript (and development in general). I wanted to try a challenge from Codewars. The challenge was to process a string through a function that would flip any words that were over 5 characters and return the original string with those flipped words. Here's the code I came up with (It did work!).
//this function turns each word into an array that will get flipped.
let wordFlipper = (word) => {
var splitWord = word.split(''); //convert word to array
var reversedWord = splitWord.reverse(); //flips the indexes for the array
var joinReversedWord = reversedWord.join('').toString(); //turns array back to a string.
return joinReversedWord;
}
function spinWords(phrase){
let finalArray = [];
let wordsToArray = phrase.split(' ');
const processFlipWords = wordsToArray.forEach(word => {
if (word.toString().length > 4) {
var flippedWord = wordFlipper(word); //here's where we call the function wordFlipper()
finalArray.push(flippedWord);
}
else {
finalArray.push(word);
}
});
return finalArray.join(' ');
}
How would you experts suggest writing this? I'm sure I'm not being too efficient at writing this code.
Thank you!
Here's what it looks like inside codewars!
I'd use a regular expression to match 5 or more word characters (\w{5,}), and have a replacer function (String.replace()) return the reversed (reverse()) word:
const spinWords = phrase => phrase.replace(
/\w{5,}/g,
word => [...word].reverse().join('')
);
console.log(spinWords('foo barbar more words go here'));
\w matches a word character - something from A to Z, case-insensitive, or a digit, or an underscore.
The brackets indicates the number of times to repeat the previous token. {5,} starts with a 5 (so, "at least 5") and has nothing after the comma ("up to any number").
Then /g, the global flag, matches and replaces every substring that matches this pattern, not just the first.
The callback function runs for every matched substring, where the argument is the matched substring, and what is returned gets replaced at that point in the original string.

Show array as scentence except first item

How can I output an array as a scentence except the (1) item? Let's say the content of the array is: ["!report","Jay","This","is","the","reason"];
I tried this to output the items after the (1): (args.slice(1));however the output now is: "This,is,the,reason", how could I make it output as a normal scentence?
If you don't want to use built in methods, you can append each word
in the array starting at index 1 (second item).
// List of words
var words = ["!report","Jay","This","is","the","reason"];
// Empty string
var sentence = "";
// Loop through array starting at index 1 (second item)
for (let i = 1; i < words.length; i++) {
// Keep appending the words to sentence string
sentence = sentence + words[i] + " ";
}
// Print the sentence as a whole
console.log(sentence);
Or using built in functions:
// Array of strings
var array = ["!report","Jay","This","is","the","reason"];
// Cut off the first element, words is still an array though
var words = array.slice(1)
// Join each element into a string with spaces in between
var sentence = words.join(" ")
// Print as full sentence
console.log(sentence)
Output:
"Jay This is the reason"
You could slice from the second element and join the array.
console.log(["!report","Jay","This","is","the","reason"].slice(2).join(' '));
.slice() returns a new array, so when you access it as a whole, you often see a comma separated list of the array values.
But, .slice() along with .join() does the trick. .join() allows you to "join" all the array values as a single string. If you pass an argument to .join(), that argument will be used as a separator.
You can then just concatenate a period (.) to the end of the string.
console.log(["!report","Jay","This","is","the","reason"].slice(1).join(" ") + ".");
The output you desire is not very clear (do you want to remove only the first item or also the second). However the methods are the same:
you can use destructuring assignment syntax if you're es6 compliant
const arr = [a,b,...c] = ["!report","Jay","This","is","the","reason"];
let sentence = c.join(" ");
// or
let sentence2 = c.toString().replace(/,/g," ");
console.log (sentence," - ",sentence2);
or simply replace with regex and a correct pattern
const arr = ["!report","Jay","This","is","the","reason"];
let sentence = arr.toString().replace(/^[A-z! ]+?,[A-z ]+?,/,"").replace(/,/g," ");
// or
let sentence2 = arr.toString().replace(/^[A-z! ]+?,/,"").replace(/,/g," ");
console.log (sentence," - ",sentence2);
Here it is, check fiddle comments for code explanation.
var a = ["!report","Jay","This","is","the","reason"];
//removes first element from array and implodes array with spaces
var sentence = a.slice(1).join(" ");
console.log(sentence);

Javascript regex match and get values from string

I've got a string of text which can have specific tags in it.
Example: var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
What I'm trying to do is do a regex match against the <pause #></pause> tag.
For each tags found, in this case it's <pause 4></pause> and <pause 7></pause>. What I want is to grab the value 4 and 7, and the string length divided by for the string in between the <pause #>...</pause> tags.
What I have for now is not much.
But I cant figure out how to grab all the cases, then loop through each one and grab the values I'm looking for.
My function for this looks like this for now, it's not much:
/**
* checkTags(string)
* Just check for tags, and add them
* to the proper arrays for drawing later on
* #return string
*/
function checkTags(string) {
// Regular expresions we will use
var regex = {
pause: /<pause (.*?)>(.*?)<\/pause>/g
}
var matchedPauses = string.match(regex.pause);
// For each match
// Grab the pause seconds <pause SECONDS>
// Grab the length of the string divided by 2 "string.length/2" between the <pause></pause> tags
// Push the values to "pauses" [seconds, string.length/2]
// Remove the tags from the original string variable
return string;
}
If anyone can explain my how I could do this I would be very thankful! :)
match(/.../g) doesn't save subgroups, you're going to need exec or replace to do that. Here's an example of a replace-based helper function to get all matches:
function matchAll(re, str) {
var matches = [];
str.replace(re, function() {
matches.push([...arguments]);
});
return matches;
}
var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
var re = /<pause (\d+)>(.+?)<\/pause>/g;
console.log(matchAll(re, string))
Since you're removing tags anyways, you can also use replace directly.
You need to make a loop to find all matched groups of your RegExp pattern in the text.
The matched group is an array containing the original text, the matched value and the match text.
var str = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
function checkTags(str) {
// Regular expresions we will use
var regex = {
pause: /<pause (.*?)>(.*?)\<\/pause>/g
}
var matches = [];
while(matchedPauses = regex.pause.exec(str)) {
matches.push([matchedPauses[1], matchedPauses[2].length /2]);
};
return matches;
}
console.log(checkTags(str));
As a start point since you have not much so far you could try this one
/<pause [0-9]+>.*<\/pause>/g
Than to get the number out there you match again using
/[0-9]+>/g
To get rid of the last sign >
str = str.slice(0, -1);

How to compare a string with each string in a list in js?

The problem is,
Given a word and a list of possible anagrams, selects the correct sublist.
Given "listen" and a list of candidates like "enlists" "google"
"inlets" "banana"` the program should return a list containing
"inlets".
The test cases given are of type:
var anagram = require('./anagram');
describe('Anagram', function() {
xit("detects simple anagram",function() {
var subject = anagram("ant");
var matches = subject.matches(['tan', 'stand', 'at']);
expect(matches).toEqual(['tan']);
});
});
Here is what I have been thinking,
Take in the given word, split each character and sort it alphabetically
Take in the list, split it to words, take each word and split each character and sort it alphabetically
Compare the result of 1 with 2, if a string matches, return its original form.
But the problem is, I don't know how to begin, please help.
Yeah, your thinking is correct, here's how you can implement it:
var anagrams = function( input, wordlist ){
// sort the input word
var sortedinput = input.split('').sort().join('');
// filter the array by checking if...
return wordlist.filter( function( word ){
// ...the word after sorting matches the sorted input
return word.split('').sort().join('') == sortedinput;
});
}
anagrams( 'listen', ["enlists", "google", "inlets", "banana"] );
// ["inlets"]
http://jsfiddle.net/2kkvw4u5/
After splitting the current word into char array:
iterate over the list of words;
check the length of the array if it's equal with the compared word char array;
sort the compared word char array and the current word char array, and check each elements if are equal for all indexes in that array.

how to get array of sentences and words passing as parameter to a function in javascript?

I have a function say
var init = function(data){
all sentences: " I have to get all the sentences and return an array containing all sentences"
all words : "this method should return an array of words in ‘Data’ when there is no parameter passed in. Optionally, when there is a parameter passed in that is a number, return the words in the sentence indicated by the input parameter"
all reverse sentences: "this method is the same as all Sentences, except it should return the sentences in reverse order"
reverse words :" same as all words but in reverse order"
countWordsBeginningWith:" this method should return the amount of words that begin with an inputted string. The optional second parameter should determine what sentence the words come from when present."
thanks
I think what you need to do is decompose your argument (assuming it's a string) into an array. For instance:
function getAllWords(sentences) {
var result = sentences.split(' ');
return result;
}
var init = function(data){
var result = [];
result['words'] = getAllWords(data.text);
// result['sentences'] = getAllSentences(data.text);
// result['sentencesreversed'] = getReverseSentences(data.text);
// result['sentencewords'] = getReverseWords(data.text);
// result['beginswith'] = getWordsBeginningWith(data.text, data.beginswith);
return result;
}
var getIt = {
'beginswith': 't',
'text': 'This is stuff. I am a sentence. Stuff happens now.'
};
console.log(init(getIt));
This is a very simplistic answer, not taking into account for periods, commas, and other bits. But that's the general answer. Some for loops and/or RegEx's may occur after this point, buyer beware.
In Javascript you can pass any data structure as a function parameter.
First learn how to construct an array of strings to contain you word or sentences. Once you have accomplished this it will be straightforward.

Categories