Program to find same words from 2 strings javascript - javascript

I was asked this question in an interview where I failed to answer.
Here's my try:
str1 = "This is string 1";
str2 = "This is string 2";
let similarWords = [];
splittedStr1 = str1.split(" ");
splittedStr2 = str2.split(" ");
console.log(splittedStr1);
console.log(splittedStr2);
for (i = 0; i < splittedStr1.length; i++) {
for (j = i; j < splittedStr2.length; j++) {
if (splittedStr1[i] = splittedStr2[j]) {
similarWords.push(splittedStr1[i]);
}
}
}
console.log(similarWords);
This outputs:
[
"This",
"is",
"string",
"2",
"is",
"string",
"2",
"string",
"2",
"2"
]
I'm wondering what did I miss?
I've shown what I tried above.

The problem with the code is that in the inner for loop, you are using the assignment operator (=) instead of the comparison operator (== or ===) when checking if splittedStr1[i] is equal to splittedStr2[j].
To do this, you should change the assignment operator to a comparison operator. And then you also need to check if the word is already added in the similarWords array before adding it again.
Try this.
let str1 = "This is string 1";
let str2 = "This is string 2";
let similarWords = [];
let splittedStr1 = str1.split(" ");
let splittedStr2 = str2.split(" ");
for (i = 0; i < splittedStr1.length; i++) {
for (j = 0; j < splittedStr2.length; j++) {
if (splittedStr1[i] === splittedStr2[j] && !similarWords.includes(splittedStr1[i])) {
similarWords.push(splittedStr1[i]);
}
}
}
console.log(similarWords);

Maybe they wanted something like this.
const str1 = "This is string 1";
const str2 = "This is string 2";
const words = new Set(str1.split(' ')); // Set(4) {'This', 'is', 'string', '1'}
str2.split(' ') // ['This', 'is', 'string', '2']
.filter(word => words.has(word)); // Only keep the words from str2 that are also in str1

Related

How would I go about splitting a string into characters - Javascript [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 1 year ago.
Improve this question
I want to split a string, such as this:
"Hello $id1, how are you $id2 etc...",
but "$idInt" should not be split:
const test = [
"$id1",
"$id2",
"$id3"
]
let str = "test $id1!";
str = str.split("");
// wanted result: ["t", "e", "s", "t", " ", "$id1", "!"]; 
// actual result: ["t", "e", "s", "t", " ", "$", "i", "d", "1" "!"]
This would take anything from the "test" array and not split it with every sepparate character.
I only searched for other resources but I haven't been able to find something that does what I want this to do exactly.
I also got this code:
let reg = /\%\[a-zA-Z0-9]\:[0-9]+\%/gim;
let yourstring = 'Some thinger %09ff:13%';
let matches = reg.exec(yourstring);
let records = [];
let pieces = [];
if (matches != null) {
for (let [i, match] of Array.from(matches).entries()) {
let start = yourstring.indexOf(match);
let end = match.length + start;
records.push({
start: start,
end: end,
match: match,
});
}
records.sort((a, b) => (a.start > b.start ? 1 : a.start < b.start ? -1 : 0));
if (records[0].start > 0) {
records = [{
start: 0,
end: 0,
match: ""
}].concat(records);
}
for (let i = 1; i < records.length; i++) {
pieces.push(yourstring.slice(records[i - 1].end, records[i].start).replace(......)); // replace goes here
pieces.push(records[i].match);
}
yourstring = pieces.join("")
} else {
yourstring = yourstring.replace(.......) // replace goes here
} 
but it's regex and I want a set of strings to not be replaced rather than this here with regex
I would propose using match instead of split:
let s = "Hello %id:1%, how are you %id:2% etc...";
let result = s.match(/%id:\d+%|./gs);
console.log(result);
You should use the split function like this:
let str1 = "test %id:1%!"
let arr1 = str1.split('%')
let test = [];
// arr1 will become ['test ','id:1','!']
// every alternate one will become one of the usable one.
arr1.forEach((x,index)=>{
if (index%2 == 1) {
// push in test and add the '%'s back in.
test.push(`%${x}%`)
}
})
Trincot's answer is better but I already wrote this so here it is...
var str = "Hello %id:1%, how are you %id:2% etc...";
console.log(splitStr(str));
function splitStr(str) {
var is_var = false;
var chars = [];
var group = '';
for (var i = 0; i < str.length; i++) {
let char = str[i];
if (is_var) {
group += char;
if ('%' == char) {
chars.push(group);
group = '';
is_var = false;
}
} else {
if ('%' == char) {
group += char;
is_var = true;
}else{
chars.push(char);
}
}
}
return chars;
}

How can I find the EXACT amount of matching words in a string?

for a project I've written a function which includes the following:
var filtering_words = ['alpha', 'beta', 'gamma'];
//finding matching words
var prohibited_words = filtering_words;
for (var i = 0; i < prohibited_words.length; i++) {
if (value.indexOf(prohibited_words[i]) > -1) {
user_report['matching_words'].push(prohibited_words[i]);
user_report['matching_words_amount'] = user_report['matching_words'].length;
}
}
String: 'alpha beta beta gamma'
For now I just get all the matching words.
So my result would look like that: ['alpha'], ['beta'], ['gamma']
But I would also like to know how often a "filtering_word" is in my string. In this case I would want to know that there are actually 2 betas...
Any idea?
Cheers
Store the results in an Object instead of an Array, so that you could map the filtered word to the number of occurrences.
To find the number of occurrences, use a RegExp with the g flag to get an array of all occurrences (and i flag for a case insensitive search), then get the resulting array length.
var user_report = { matching_words: {} }
var value = 'lambdabetaalphabeta'
var filtering_words = ['alpha', 'beta', 'gamma'];
var prohibited_words = filtering_words;
for (var i = 0; i < prohibited_words.length; i++) {
var matches = (value.match(new RegExp(prohibited_words[i], 'ig')) || []).length
if (matches) {
var matching_words = user_report['matching_words'] || {};
matching_words[prohibited_words[i]] = matches
}
}
user_report['matching_words_amount'] = Object.keys(user_report['matching_words']).length
console.log(user_report)
This code gives you the 'unnecessary' words:
let arr = ['alpha', 'beta', 'gamma', 'beta'];
for(let i = 0;i < arr.length;i++){
for(let j = 0;j < arr.length;j++){
if(i !== j){
if(arr[i] === arr[j]){
let [sameWords] = arr.splice(i, 1)
console.log(sameWords)
}
}
}
}
You can use reduce() to populate a dictionary with prohibited words and their frequencies:
var str = "alpha beta yo alpha beta lorem ipsum gamma alpha",
filtering_words = ['alpha', 'beta', 'beta', 'gamma'];
// divide the str into words, then check if a word is prohibited and add (increment) it to the dictionary
var result = str.split(' ').reduce(function(acc,v)
{
if (filtering_words.indexOf(v)>=0)
{
acc[v] = (acc[v] || 0) + 1;
}
return acc
},{})
console.log(result)
// {alpha: 3, beta: 2, gamma: 1}

Order string match results by max match

I want to search all match in a string and return all result ordered by max match results, let's say I have some strings:
var strArray = [
"This is my number one string",
"Another string that contains number",
"Just for example string"
];
// Results of search "another number" should be:
var resultArrayOfIndexes = [1, 0];
So far I can search in a string but it returns all indexes where is at least one match, but I want the result array to be sorted by max count of matches.
My code:
function findMatch(list, phrase) {
var preparedList = [],
value = "";
if (config.get("list").match.enabled) {
for (var i = 0, length = list.length; i < length; i += 1) {
value = config.get("getValue")(list[i]);
var words = phrase.split(' ');
var listMatchArr = [];
$.each(words, function(idx, word) {
var W = word.replace(/[\W_]+/g, ""); // match on alphaNum chars only
if (match(value, W) && $.inArray(i, listMatchArr) == -1) { //phrase
preparedList.push(list[i]);
listMatchArr.push(i);
};
});
}
} else {
preparedList = list;
}
return preparedList;
}
I'm assuming a case-insensitive search is required.
The following code changes the phrase into an array of individual words, then maps the list to get back an array of objects in the form {index: 0, matches:1}, then filters out the ones where there were no matches, then sorts, then maps again to get just the indices.
function findMatch(list, phrase) {
var searchTerms = phrase.toLowerCase().split(/\s+/);
return list.map(function(v, i) {
v = v.toLowerCase();
return {
index: i,
matches: searchTerms.reduce(function(a, c) {
return a + (v.indexOf(c) !=-1 ? 1 : 0);
}, 0)
};
})
.filter(function(v) { return v.matches > 0; })
.sort(function(a, b) { return b.matches - a.matches; })
.map(function(v) { return v.index; });
}
var strArray = [
"This is my number one string", "Another string that contains number","Just for example string"
];
console.log(findMatch(strArray, "another number"));
Or expand the following for basically the same thing with ES6 features:
function findMatch(list, phrase) {
var searchTerms = phrase.toLowerCase().split(/\s+/);
return list.map(function(v, i) {
v = v.toLowerCase();
return {
index: i,
matches: searchTerms.reduce((a, c) => a + (v.includes(c) ? 1 : 0), 0)
};
})
.filter(v => v.matches > 0)
.sort((a, b) => b.matches - a.matches)
.map(v => v.index);
}
var strArray = [
"This is my number one string", "Another string that contains number","Just for example string"
];
console.log(findMatch(strArray, "another number"));
You can use regex to match your phrase as well as count how many words are matches in your string if you are familiar with regex.
Assume that you want to know how many words were matched as well, you can store it as an array of objects where each object store the count number and the target string.
var strArray = [
"This is my number one string", "Another string that contains number", "Just for example string"
];
function findMatch(list, phrase){
var words = phrase.split(" ");
var pattern = "";
var length = words.length;
// create pattern for regex match
for(var i = 0; i < length; i++){
pattern += words[i];
if(i < length-1){
pattern += "|";
}
}
var counts = [];
var re = new RegExp(pattern,"g");
for(var i = 0; i < list.length; i++){
var count = (list[i].toLowerCase().match(re) || []).length;
//add to array if matched
if(count > 0){
counts.push({count:count,string:list[i]});
}
}
//sort by max match
counts.sort(function(a,b){
return b.count-a.count;
});
console.log(counts);
}
findMatch(strArray, "another number");
The result will look something like:
[ { count: 2, string: 'Another string that contains number' },
{ count: 1, string: 'This is my number one string' },
{ count: 0, string: 'Just for example string' } ]

Iterate through an array and remove all values that contain a specific word

I have this array:
suggestions = [ "the dog",
"the cat",
"the boat",
"boat engine",
"boat motor",
"motor oil"
];
How can I iterate through the array and remove all the entries that contain a specific word?
For example, removing all entires that contain the word "the", so the array becomes:
[ "boat engine",
"boat motor",
"motor oil"
];
It's probably easier to create a new array:
var correct = [],
len = suggestions.length,
i = 0,
val;
for (; i < len; ++i) {
val = suggestions[i];
if (val.indexOf('the') === -1) {
correct.push(val);
}
}
I would use this setup:
var suggestions = [
"the dog",
"the cat",
"he went then",
"boat engine",
"another either thing",
"some string the whatever"
];
function filterWord(arr, filter) {
var i = arr.length, cur,
re = new RegExp("\\b" + filter + "\\b");
while (i--) {
cur = arr[i];
if (re.test(cur)) {
arr.splice(i, 1);
}
}
}
filterWord(suggestions, "the");
console.log(suggestions);
DEMO: http://jsfiddle.net/Kacju/
It loops backward, correctly checking for the word to look for (by using the \b identifier as a word boundary), and removes any matches.
If you want to generate a new array containing the matches, loop normally and just push any non-matches to the new array. You could use this:
var suggestions = [
"the dog",
"the cat",
"he went then",
"boat engine",
"another either thing",
"some string the whatever"
];
function filterWord(arr, filter) {
var i, j, cur, ret = [],
re = new RegExp("\\b" + filter + "\\b");
for (i = 0, j = arr.length; i < j; i++) {
cur = arr[i];
if (!re.test(cur)) {
ret.push(cur);
}
}
return ret;
}
var newSuggestions = filterWord(suggestions, "the");
console.log(newSuggestions);
DEMO: http://jsfiddle.net/Kacju/1/
Try using a regex
var suggestions = [ "the dog",
"the cat",
"the boat",
"boat engine",
"boat motor",
"motor oil"
];
var filtered = [],
len = suggestions.length,
val,
checkCondition = /\bthe\b/;
for (var i =0; i < len; ++i) {
val = suggestions[i];
if (!checkCondition.test(val)) {
filtered.push(val);
}
}
check fiddle
Using the power of ECMAScript5 :
suggestions.reduce (
function (r, s) {!(/\bthe\b/.test (s)) && r.push (s); return r; }, []);

how to use indexOf to determine if a certain set of characters in Javascript

let's say I have an array of 30 strings.
I want to determine if the string contains let's say characters of "ea" and I will then alert the strings that contains ea.
I want to use indexOf how can I do that?
let's say if I have an array of
var new = ["banana","apple","orange"];
I tried something like...
new_an = new.indexOf("an");
for (i=0; i < new.length;i++ )
{
if (new_an = -1)
{
alert(new[i]);
}
}
so only banana and orange has an in it and I I only want to alert those two....but not sure what am I missing here...
indexOf is returning -1 if there is no match in given string. You can do like this:
var arr = ["string 1", "string 2", "string 3", "test"];
for(var i = 0; i < arr.length; i++) {
if(arr[i].indexOf('str') != -1) {
console.log(arr[i]);
}
}
The output of this example should be: string 1, string 2, string 3
Use following solution in loop over the array of string.
Example
Search a string for "welcome":
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
The result of n will be:
13
See here for more details
I would simply loop through the array and then check with String.contains() whether your search string is in the original string.
str.contains(searchString);
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
j is index of str in array.
One way using filter;
var it = ["aea", "b", "c", "dea", "eee", "fea"];
var find = "ea";
var matches = it.filter(function(el) {
return el.indexOf(find) > -1;
});
alert(matches);

Categories

Resources