Finding common strings in javascript - javascript

I am trying to find common strings in given two strings.
Example:
string1 = "mega,cloud,two,website,final"
string2 = "window,penguin,literature,network,fun,cloud,final,sausage"
answer = "cloud,final,two"
So far this is what i got:
function commonWords(first, second) {
var words = first.match(/\w+/g);
var result = "";
words.sort();
for(var i = 0; i < words.length; i++){
if(second.includes(words[i])){
result = result.concat(words[i]);
result += ",";
}
}
result = result.substr(0, result.length -1);
return result;
}
But the result that i got is :
answer = cloud,final
Can you help me out please? First time asking question on StackOverFlow, so sorry for the typing.

What I would do is first split on the two strings, then do a reduce and check if the other string includes the current string. If so add them to a new array.
const string1 = "mega,cloud,two,website,final"
const string2 = "window,penguin,literature,network,fun,cloud,final,sausage"
const array1 = string1.split(',')
const array2 = string2.split(',')
const result = array1.reduce((arr, val) => array2.includes(val) ? arr.concat(val) : arr, [])
console.log(result)
// Convert it to a string if desired
console.log(result.toString())

Try the following:
string1 = "mega,cloud,two,website,final"
string2 = "window,penguin,literature,network,fun,cloud,final,sausage";
var arr1= string1.split(",");
var arr2 = string2.split(",");
var result = [];
arr1.forEach(function(str){
arr2.forEach(function(str2){
if(str2.indexOf(str) != -1)
result.push(str);
});
});
var answer = result.join(",");
console.log(answer);

The problem with your function is you also converting the string to into second as an array.
function commonWords(first, second) {
var words = first.match(/\w+/g); // word is a array type
var result = "";
words.sort();
for(var i = 0; i < words.length; i++){
if(second.includes(words[i])){ //second should be string type
result = result.concat(words[i]);
result += ",";
}
}
result = result.substr(0, result.length -1);
return result;
}
Or you can try this
first = "mega,cloud,two,website,final"
second = "window,penguin,literature,network,fun,cloud,final,sausage"
function commonWords(first, second) {
var words = first.match(/\w+/g);
var result = "";
words.sort();
for(var i = 0; i < words.length; i++){
if(second.includes(words[i])){
result = result.concat(words[i]);
result += ",";
}
}
result = result.substr(0, result.length -1);
return result;
}
console.log(commonWords(first, second));

I would convert each string to an array of words with .split(','). Then filter the first array with .filter by checking if each item of the array is in the other one:
string1 = "mega,Cloud,two,website,final"
string2 = "window,penguin,literature,network,fun,cloud,final,sausage"
array1 = string1.toLowerCase().split(',')
array2 = string2.toLowerCase().split(',')
var a = array1.filter(word => -1 !== array2.indexOf(word));
console.log(a)
Before converting the string to an array I have applied .toLowerCase() so that the script can return cloud in the result if it appears in the first one as "Cloud" and in the second as "cloud"

Related

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

Pushing first character at last and returning the string

I was trying to find out a way where I can push the first character to the last and return the rest of the string.
suppose like reverse("aeiou") should be able to return
eioua
iouae
ouaei
uaeio
function strR(str){
var a = str.split('');
var tmp =[];
a.map (item => {tmp.unshift(item)
console.log(tmp);
})
}
strR("aeiou")
aeiou
I tried a lot seems not working . If anyone can help me would be really appreciated.
let bla = "aeiou";
for (let i = 0; i < bla.length; i++) {
bla = bla.slice(1) + bla[0];
console.log(bla);
}
Try this! Alert data can print out wherever
function myFunction() {
var str = "aeiou";
var count = str.length;
for (i = 0; i < str.length; i++) {
var res = str.substring(0, 1);
var result = str.slice(1);
var data = result + res;
str = data;
alert(data);
}
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Just use substr to remove the first character and charAt to add it to the end.
var string = 'aeiou'
i=0
while (i < 10) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
Maybe you are looking for this.
let input = "aeiou";
let chunk = input.split("");
let output = [];
for(let i=0; i<chunk.length;i++){
let last = chunk.shift();
chunk.push(last);
output.push(chunk.toString().replace(/,/g, ''));
}
console.log("Output", output.toString());
Here is one liner using Array.from and slice methods.
const str = "aeiou";
const str_arr = Array.from(
new Array(str.length),
(_, i) => `${str.slice(i, str.length)}${str.slice(0, i)}`
);
console.log(str_arr);
there is a short and easier way for do that:
function FirstToEnd (str){
return str.substr(1) + str[0]
}
and for result all possible data:
function FirstToEndAllPossible(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
str = str.substr(1) + str[0];
result.push(str);
}
return result;
}
good luck :)
Try This:
var string = 'aeiou'
i=0
while (i < string.length-1) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
You can use like this. Calling Recursion - Works for all the Strings.
var InputStr = 'aeiou';
var i = 0;
var word = [];
function callqueue(InputStr, i)
{
StringLength = InputStr.length;
i = i+1;
if (i <= StringLength)
{
firstChar = InputStr.slice(0, 1);
remainStr = InputStr.substr(1);
word.push(remainStr+firstChar);
callqueue(remainStr+firstChar, i);
}
return word;
}
output = callqueue(InputStr, i);
console.log(output);
Try below code
function strR(str){
for (let i = 0; i < str.length-1; i++) {
str = str.substr(1)+str.charAt(0);
console.log(str);
}
strR('aeiou');
Your question is not quite clear. Hope the below solution works for you.
function strR(str){
var a = str.split('');
a[a.length] = a.shift();
return a.join('');
}
strR("aeiou")
/* or */
String.prototype.firstToLast = function() {
var a = this.split('');
a[a.length] = a.shift();
return a.join('');
}
"aeiou".firstToLast();
I find using an array for this kind of string manipulation a bit more readable.
In the function below, we start with splitting the string into an array.
The second step will be using the native .shit method which returns the first item in an array (in our case, the first letter) while modifying the Lastly, as we have the first character and the rest of the string we build them into a new array where we spread (...) the modified array and adding the first character at the end. The join('') method returns a string out of the new array.
function firstToLast (str) {
const split = str.split('');
const first = split.shift();
return [...split, first].join('');
}
Hopefully it's clear and helps with what you were trying to achieve
My go-to would be to use JavaScripts built-in array methods. You can break a string into an array of single characters using split with no parameters, and put it back together using join with an empty string as a parameter.
let word = 'sydney'
function rotate (anyword) {
let wordarray= anyword.split()
let chartomove = wordarray.splice(0, 1)[0]
wordarray.push(chartomove)
return wordarray.join('')
}
rotate(word) // returns 'ydneys'

Take a string , evaluate it and find if there is a number and repeat part of string that number of times?

I was writing code and came into this problem,
You have a specific string which is in this form:
d ae2 n s
now we have to decode this in a specific way,
Split it into different parts by spaces to make an array like ["d","ae2","n","s"]
Evaluate each element of the array and find out if there is a number in it.
If there is a number then repeat the string the number of times.
Add it into the array and continue.
So the output array should be
["d","ae","ae","n","s"]
I have already tried a lot but got nothing
I have used this code earlier but it ends on the second string:
var str = "d ae2 n s"
var res = str.split(" ");
alert(res.length);
for(var x = 0; x < res.length; x++ ){
var std = res[x];
var fun = checkNum(std);
if(fun === true){
var numbers = str.match(/\d+/g).map(Number);
var index = res.indexOf(std);
var result = std.replace(/[0-9]/g, '');
var res2 = result.repeat(numbers);
res[index] = res2;
}
else{
continue;
}
for(var i = 0; i < res.length; i++ ){
console.log(res[x]);
}
}
function checkNum(t){
return /\d/.test(t);
}
// I am a terible coder :/
expected input : d ae2 n s
expected output : ["d","ae","ae","n","s"]
Using fill() and flatMap() methods and
regex replace
/[^0-9]/ - all non numerical chars
/[0-9]/ - all numerical chars
var str = 'd ae2 n s'
var res = str
.split(' ')
.flatMap(i =>
Array(+i.replace(/[^0-9]/g, '') || 1)
.fill(i.replace(/[0-9]/g, ''))
)
console.log(res)
You can simply loop over your array and populate an other array that will hold your result after checking for a number :
const results = [];
"d ae2 n s".split(' ').forEach(token => {
const match = token.match(/\d+/);
if (match) {
const newStr = token.split(/\d/)[0];
for (let i = 0; i < match[0]; i++) {
results.push(newStr);
}
} else {
results.push(token)
}
})
console.log(results);
You can check Seblor's answer for optimized logic. I have modified your code so that it will be easy for you to understand where you went wrong while doing this. I have added comments to your code where I have changed things:
var str = "d ae2 n s"
var res = str.split(" ");
// create a variable to store the output.
var output = [];
for(var x = 0; x < res.length; x++ ){
var std = res[x];
var fun = checkNum(std);
if(fun === true){
// map returns an array, so take the first element, it will be your number.
var numbers = str.match(/\d+/g).map(Number)[0];
var index = res.indexOf(std);
var result = std.replace(/[0-9]/g, '');
// instead of doing the repeat and updating the current index,
// push the result, i.e. the current string to be repeated "numbers" times into
// the output array.
for (var i = 0; i < numbers; i++) {
output.push(result)
}
}
else{
// if does not contain any number, push the current item to ouput
output.push (std);
continue;
}
}
function checkNum(t){
return /\d/.test(t);
}
console.log(output);
You can do:
const str1 = 'd ae2 n s';
const str2 = 'e d aefg4 m n s';
const regex = /\d+/;
const getResult = input => input.split(' ').reduce((a, c) => {
const n = c.match(regex);
return n
? [...a.concat(c.replace(n, ' ').repeat(n).trim().split(' '))]
: [...a, c];
}, []);
console.log(getResult(str1));
console.log(getResult(str2));
you can use the Array prototype reduce and filter
const input = 'd ae2 n s';
const output = input.split(' ').reduce((memory, current) => {
const numberIndex = current.split('').findIndex(c => !isNaN(c));
const newCurrent = current.split('').filter((_, index) => index !== numberIndex).join('');
if(numberIndex !== -1) {
for(let i = 0; i < parseInt(current[numberIndex]); i++) {
memory.push(newCurrent);
}
} else {
memory.push(current);
}
return memory;
}, []);
console.log(output);
Hope this helped
You can try with following:
let str = "d ae2 n s"
let split = str.split(" ")
let rx = new RegExp("[0-9]")
let res = [];
split.forEach(s => {
if(rx.exec(s) !== null) {
let rxResult = rx.exec(s)
let count = rxResult[0];
let matchIdx = rxResult[1];
for(let i = 0; i < count; i++) {
res.push(s.replace(count, ""))
}
} else {
res.push(s);
}
})

Cut JS string present in an array at every occurrance of a particular substring and append to same array

Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!
What I have:
var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
What I need:
["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$
Example:
difference.$.user.$.otherinformation should be parsed to contain:
difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.
Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.
How best can I take this to closure?
Current flawed implementation:
for(var i=0; i<array.length; i++){
// next, replace all array field references with $ as that is what autoform's pick() requires
// /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
array[i] = array[i].replace(/\.\d+\./g,".$.");
if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
console.log("Substring without .$. " + array[i].substring(0, array[i].indexOf('.$.')));
console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')));
}
}
// finally remove any duplicates if any
array = _.uniq(array);
A functional single liner could be;
var array = ["authentication.$.order", "difference.$.user.$.otherinformation"],
result = array.reduce((r,s) => r.concat(s.split(".").reduce((p,c,i) => p.concat(i ? p[p.length-1] + "." + c : c), [])), []);
console.log(result);
You can use this function inside your array loop.
var test = "difference.$.user.$.otherinformation";
function toArray(testString) {
var testArr = testString.split(".")
var tempString = "";
var finalArray = [];
for (var i = 0; i < testArr.length; i++) {
var toTest = testArr[i];
if (toTest == "$") {
tempString += ".$"
} else {
if (i != 0) {
tempString += ".";
}
tempString += toTest;
}
finalArray.push(tempString)
}
return finalArray;
}
console.log(toArray(test))
I used a Regex expression to grab everything until the last occurrence of .$ and the chopped it, until there was nothing left. Reverse at the end.
let results = [];
let found = true;
const regex = /^(.*)\.\$/g;
let str = `difference.\$.user.\$.otherinformation`;
let m;
results.push(str);
while(found) {
found = false;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(m.length > 0) {
found = true;
results.push(m[0]);
str = m[1];
}
}
}
results.push(str);
results = results.reverse();
// Concat this onto another array and keep concatenating for the other strings
console.log(results);
You will just need to loop this over your array, store the results in a temp array and keep concatenating them onto a final array.
https://jsfiddle.net/9pa3hr46/
You can use reduce as follows:
const dat = ["authentication.$.order", "difference.$.user.$.otherinformation"];
const ret = dat.reduce((acc, val) => {
const props = val.split('.');
let concat = '';
return acc.concat(props.reduce((acc1, prop) => {
concat+= (concat ? '.'+ prop : prop);
acc1.push(concat);
return acc1;
}, []));
}, [])
console.log(ret);
Actually recursion is unnecessary for this problem. You can use regular loop with subloop instead.
All you need is:
split each occurence in the array into substrings;
build a series of accumulated values from these substrings;
replace the current element of the array with this series.
Moreover, in order to make replacement to work properly you have to iterate the array in reverse order. BTW in this case you don't need to remove duplicates in the array.
So the code should look like this:
var array = ["authentication.$.order", "difference.$.user.$.otherinformation"];
var SEP = '.$.';
for (var i = array.length-1; i >= 0; i--){
var v = array[i];
var subs = v.replace(/\.\d+\./g, SEP).split(SEP)
if (subs.length <= 1) continue;
var acc = subs[0], elems = [acc];
for (var n = subs.length-1, j = 0; j < n; j++) {
elems[j * 2 + 1] = (acc += SEP);
elems[j * 2 + 2] = (acc += subs[j]);
}
array.splice.apply(array, [i, 1].concat(elems));
}
console.log(array);
Use a simple for loop like below:
var str = "difference.$.user.$.otherinformation";
var sub, initial = "";
var start = 0;
var pos = str.indexOf('.');
for (; pos != -1; pos = str.indexOf('.', pos + 1)) {
sub = str.substring(start, pos);
console.log(initial + sub);
initial += sub;
start = pos;
}
console.log(str);

Remove duplicate in a string - javascript

I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method

Categories

Resources