//Get message from textarea
var msg = $('#mytextarea').val();
//Convert string to array of letters
// eg. cata = ['c','a','t','a']
var msgLettersAsArray = msg.split('');
What I need to do now is replace the single letters,something like this
c = b;
a = e;
t = c;
a = e;
//array neeeds to be converted from this:
var array = ['c','a','t','a'];
// to this:
var array = ['b','e','c','e'];
Is there any way to achieve this?
All I need to do is replace the letters that are already in the array with letters of my choice
It's quite simple, just define a translation map and use Array.prototype.map.
var translationMap = {
c: 'b',
a: 'e',
t: 'c'
};
//returns ['b','e','c','e']
['c','a','t','a'].map(function (letter) { return translationMap[letter] || letter; });
EDIT: It seems you actually just wanted to replace letters in the string, in this case #phylax answer would be correct. There is no need to use arrays for a simple string replacement.
function replaceChars(str, map) {
var i, reg = "";
for (i in map)
reg += i;
return str.replace(
new RegExp("["+reg.replace(/(\]|-|\\)/,"\\$1")+"]",'g'),
function(char) { return map[char]; }
);
}
//Get message from textarea
var msg = $('#mytextarea').val(); // "cata"
replaceChars(msg, {c:'b', a:'e', t:'c', a:'e'}); // "bece"
Just making an answer out of my comment:
Like OP said, its ok to be done without the split(). And its possible to do with only one call to String.replace():
var map = {
c: 'b',
a: 'e',
t: 'c'
};
msg.replace(/[a-z0-9]/g, function (i) { return map[i] || i; })
The RegExp can possibly made event simpler:
msg.replace(/./g, function (i) { return map[i] || i; })
Sure, just use a for loop:
var array = ['c','a','t','a'];
for (var i = 0; i < array.length; i++)
{
var cur = array[i];
if (cur == 'c') {
array[i] = 'b';
} else if (cur == 'a') {
array[i] = 't';
} else if (cur == 't') {
array[i] = 'c';
}
}
But using an object to store these mappings can make your code even more compact:
var array = ['c','a','t','a'];
var transform = { 'c': 'b', 'a': 'e', 't': 'c' };
for (var i = 0; i < array.length; i++)
{
array[i] = transform[array[i]];
}
not tested but it should work
var replaxe = {
'c':'b',
'e':'d'
},
array = ['c','e'],
result = [];
for(var item in array){
result.push(replaxe[item]);
}
console.log(result);
RUN THIS IN YOUR FIRE BUG CONSOLE
var array = ['c','a','t','a'];
var myarray = [];
for(i=0; i<=array.length; i++)
{
if(array[i] == 'c' )
{
array[i] = 'b'
}
if(array[i] == 'a' )
{
array[i] = 'e'
}
if(array[i] == 't' )
{
array[i] = 'c'
}
if(array[i] == 'a' )
{
array[i] = 'a'
}
}
console.log(myarray);
I would recommend using a switch-case for every element in the array.
for (i in array) {
switch (array[i]) {
case "c":
array[i] = "b";
break;
case "a":
array[i] = "e";
break;
case "t":
array[i] = "c";
break;
}
}
Related
I want to write a function that replaces all the vowels (a,e,i,o,u) in a string and keeps one separator ('') between consonants. For example:
Input: 'kkkeoiekkk'
Output: ['kkk', '', 'kkk']
My try:
function split(para) {
let regex = /[a|e|i|o|u]/g;
let arr = para.replace(regex, '-').split('-');
for (let i = 0; i < str.length; i++) {
if (arr[i] === '' && arr[i - 1] === '') {}
}
return arr
}
Right now for the input split('hheeooook') I get back [ 'h', '', '', '', 'k' ] instead of ['h', '', 'k']. Thanks for everyone reading or pointing out what is wrong with my function.
Here is a slight variation on your attempt. It is mainly the regex which needed change.
function split (para) {
let regex = /[aeiou]+/g;
let arr = para.replace(regex, ' ').trim().split(' ');
return arr
}
console.log(split('kkhkeoiektr'));
console.log(split('akkeoihhkoo'));
console.log(split('kkeoihhkoo'));
Here is a solution without regex:
function split(para) {
let res = [];
let tmp = '';
for (let i = 0; i < para.length; i++) {
if ('aeiou'.includes(para[i])) {
if (tmp.length) {
res.push(tmp);
res.push('');
tmp = '';
}
} else {
tmp += para[i];
}
}
if (tmp.length) {
res.push(tmp);
} else {
if (res.length > 0)
res.pop();
}
return res;
}
console.log(split('kkkeoiekkk'));
console.log(split('kkkeoiekkka'));
console.log(split('kkkeoiekkkak'));
You can iterate to split the string.
var dict = {"a":1,"e":1,"i":1,"o":1,"u":1};
const src = 'kkkeoiekkk0qwert';
var pre = "";
var result = [];
for(var i = 0; i < src.length; i++){
var char = src.charAt(i);
console.log(char);
console.log(pre);
if(dict[char]){
if(pre){
result.push(pre);
pre = "";
}
}else{
pre += char;
}
}
if(pre){
result.push(pre);
}
An alternative using reg.exec:
function split (para) {
let res = [""], reg = /[^aeiou]+/g, match;
while(match = reg.exec(para)) res.push(match[0], "");
return res.slice(1, res.length - 1);
}
console.log(split('kkhkeoiektr'));
console.log(split('akkeoihhkoo'));
console.log(split('kkeoihhkoo'));
console.log(split('kkkk'));
console.log(split('aeiou'));
I am writing a function called "countStr".
I need to return an object where each key is a word in the given string, with its value being how many times that word appeared in the given string. If the string is empty it must return an empty object.
Here's my function so far:
function countStr(str) {
myObject = {};
if(str.length === 0) {
return myObject;
} else {
myArray = str.split(' ');
for(var i = 0; i < myArray; i++) {
var key = myArray[i];
if(myObject.hasOwnProperty(key)) {
myObject[key]++;
} else {
myObject[key];
}
}
return myObject;
}
}
var output = countStr('ask me lots get me lots');
console.log(output); // --> IT MUST OUTPUT {ask: 1, me: 2, lots: 2, get: 1}
Can you tell me how to fix it?
There are small issues with your code.
You need to iterate from zero to the length of the array.
You need to initialize the object items with 1 in the else case.
You should use local variables with the var to avoid polluting your top level namespace.
Here is the fixed version:
function countStr(str) {
var myObject = {};
if(str.length === 0) {
return myObject;
} else {
var myArray = str.split(' ');
for(var i = 0; i < myArray.length; i++) {
var key = myArray[i];
if(myObject.hasOwnProperty(key)) {
myObject[key]++;
} else {
myObject[key] = 1;
}
}
return myObject;
}
}
var output = countStr('ask me lots get me lots');
console.log(output);
You can use Array#reduce() like this
function countStr(str) {
return str.trim().length ? str.split(' ').reduce((o,s)=>{
o[s] = o[s] || 0;
o[s]++;
return o;
}, {}) : {};
}
var output = countStr('ask me lots get me lots');
console.log(output); // --> {ask: 1, me: 2, lots: 2, get: 1}
Other wise in your code, you were missing Array.length in your for condition and the else should be like myObject[key]=1
function countStr(str) {
myObject = {};
var myArray = [];
if(str.length === 0) {
return myObject;
} else {
myArray = str.split(' ');
for(var i = 0; i < myArray.length; i++) {
var key = myArray[i];
if(myObject.hasOwnProperty(key)) {
myObject[key]++;
} else {
myObject[key]=1;
}
}
return myObject;
}
}
var output = countStr('ask me lots get me lots');
console.log(output);
I'd like to return the variable newString with only vowels capitalized. Not sure how to proceed. Tried using an if/else block but my logic wasn't correct.
function LetterChanges(str) {
var newArray = [];
for (var i = 0; i < str.length; i++) {
var strCode = str.charCodeAt(i) + 1;
var strLetter = String.fromCharCode(strCode);
newArray.push(strLetter);
var newString = newArray.join("");
}
return newString;
}
LetterChanges("hello");
This is different from your approach, but you can do this:
function LetterChanges(str) {
return str.toLowerCase().replace(/[aeiou]/g, function(l) {
return l.toUpperCase();
});
}
console.log(LetterChanges("The Quick Brown Fox Jumped Over The Lazy Dog"));
Here's an approach that's closer to your attempt and uses somewhat simpler concepts:
function LetterChanges(str) {
var newArray = [];
for (var i = 0; i < str.length; i++) {
var ch = str.charAt(i);
if ('aeiouAEIOU'.indexOf(ch) !== -1) {
newArray.push(ch.toUpperCase());
} else {
newArray.push(ch.toLowerCase());
}
}
return newArray.join("");
}
Split, map, join.
var vowels = 'aeiou';
var text = 'my random text with inevitable vowels';
var res = text.split('').map(function(c){
return (vowels.indexOf(c) > -1) ? c.toUpperCase() : c;
});
See the fiddle: http://jsfiddle.net/zo6j89wv/1/
Strings are Collections of word-characters, so you can directly access each part of the string:
var foo = 'bar';
console.log(foo[0]); // outputs 'b'
Hence you can extend this to uppercase the output:
console.log(foo[0].toUpperCase() // outputs 'B'
To do this without regex, you can set the string to lower case, then iterate once over, calling toUpperCase() on each vowel.
function letterChanges(string){
var vowels = 'aeiou';
var lowerString = string.toLowerCase();
var result = '';
for( var i=0; i<lowerString.length; i++){
if( vowels.indexOf( lowerString[i] ) >= 0 ){ //if lowerString[i] is a vowel
result += lowerString[i].toUpperCase();
} else {
result += lowerString[i]
}
}
return result;
}
const vowelSound = string => {
let res = string.split("").filter(item => item === 'a' || item === 'i' || item === 'e' || item === 'o' || item === 'u')
return res.join("")
}
This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 8 years ago.
I'm looking for an easy way of removing a duplicate value from an array. I figured out how to detect if there is a duplicate or not, just I don't know how to "push" it from the value. For example, if you go to the link provided, and then type, "abca" (press return/enter key after each letter).. it will alert "duplicate!"
But I also want to figure out how to remove that duplicate from the textarea?
http://jsfiddle.net/P3gpp/
This is the part that seems to not be working ::
sort = sort.push(i);
textVal = sort;
return textVal;
Why do it the hard way, it can be done more easily using javascript filter function which is specifically for this kind of operations:
var arr = ["apple", "bannana", "orange", "apple", "orange"];
arr = arr.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
});
---------------------
Output: ["apple", "bannana", "orange"]
Based on user2668376 solution, this will return a new array without duplicates.
Array.prototype.removeDuplicates = function () {
return this.filter(function (item, index, self) {
return self.indexOf(item) == index;
});
};
After that you can do:
[1, 3, 3, 7].removeDuplicates();
Result will be; [1, 3, 7].
These are the functions I created/use for removing duplicates:
var removeDuplicatesInPlace = function (arr) {
var i, j, cur, found;
for (i = arr.length - 1; i >= 0; i--) {
cur = arr[i];
found = false;
for (j = i - 1; !found && j >= 0; j--) {
if (cur === arr[j]) {
if (i !== j) {
arr.splice(i, 1);
}
found = true;
}
}
}
return arr;
};
var removeDuplicatesGetCopy = function (arr) {
var ret, len, i, j, cur, found;
ret = [];
len = arr.length;
for (i = 0; i < len; i++) {
cur = arr[i];
found = false;
for (j = 0; !found && (j < len); j++) {
if (cur === arr[j]) {
if (i === j) {
ret.push(cur);
}
found = true;
}
}
}
return ret;
};
So using the first one, this is how your code could look:
function cleanUp() {
var text = document.getElementById("fld"),
textVal = text.value,
array;
textVal = textVal.replace(/\r/g, " ");
array = textVal.split(/\n/g);
text.value = removeDuplicatesInPlace(array).join("\n");
}
DEMO: http://jsfiddle.net/VrcN6/1/
You can use Array.reduce() to remove the duplicates. You need a helper object to keep track of how many times an item has been seen.
function cleanUp()
{
var textBox = document.getElementById("fld"),
array = textBox.value.split(/\r?\n/g),
o = {},
output;
output = array.reduce(function(prev, current) {
var key = '$' + current;
// have we seen this value before?
if (o[key] === void 0) {
prev.push(current);
o[key] = true;
}
return prev;
}, []);
// write back the result
textBox.value = output.join("\n");
}
The output of the reduce() step can be used directly to populate the text area again, without affecting the original sort order.
Demo
You can do this easily with just an object:
function removeDuplicates(text) {
var seen = {};
var result = '';
for (var i = 0; i < text.length; i++) {
var char = text.charAt(i);
if (char in seen) {
continue;
} else {
seen[char] = true;
result += char;
}
}
return result;
}
function cleanUp() {
var elem = document.getElementById("fld");
elem.value = removeDuplicates(elem.value);
}
arr3 = [1, 2, 3, 2, 4, 5];
unique = [];
function findUnique(val)
{
status = '0';
unique.forEach(function(itm){
if(itm==val){
status=1;
}
})
return status;
}
arr3.forEach(function(itm){
rtn = findUnique(itm);
if(rtn==0)
unique.push(itm);
});
console.log(unique); // [1, 2, 3, 4, 5]
I'm a newbie to the JavaScript world. As the title mentions, I want to know whether there is any pre-built method in JavaScript to find all possible permutations of a given string.
For example, given the input:
the
Desired output:
the
teh
eht
eth
het
hte
//string permutation
function permutation(start, string) {
//base case
if ( string.length == 1 ) {
return [ start + string ];
} else {
var returnResult = [];
for (var i=0; i < string.length; i++) {
var result = permutation (string[i], string.substr(0, i) + string.substr(i+1));
for (var j=0; j<result.length; j++) {
returnResult.push(start + result[j]);
}
}
return returnResult;
}
}
permutation('','123') will return
["123", "132", "213", "231", "312", "321"]
function permutations(str){
if (str.length === 1) {
return str;
}
var permut = [];
for (var i=0; i<str.length; i++){
var s = str[0];
var _new = permutations(str.slice(1, str.length));
for(var j=0; j<_new.length; j++) {
permut.push(s + _new[j]);
}
str = str.substr(1, str.length -1) + s;
}
return permut;
}
permutations('the');
//output returns:[ 'the', 'teh', 'het', 'hte', 'eth', 'eht' ]
No pre-built, but writing such function is possible.. here is one relatively simple way using two functions:
function FindAllPermutations(str, index, buffer) {
if (typeof str == "string")
str = str.split("");
if (typeof index == "undefined")
index = 0;
if (typeof buffer == "undefined")
buffer = [];
if (index >= str.length)
return buffer;
for (var i = index; i < str.length; i++)
buffer.push(ToggleLetters(str, index, i));
return FindAllPermutations(str, index + 1, buffer);
}
function ToggleLetters(str, index1, index2) {
if (index1 != index2) {
var temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
}
return str.join("");
}
Usage:
var arrAllPermutations = FindAllPermutations("the");
Live test case: http://jsfiddle.net/yahavbr/X79vz/1/
This is just basic implementation, it won't remove duplicates and has no optimization. However for small strings you won't have any problem, add time measure like in the above test case and see what's your reasonable limit.
This is similar but finds all anagrams/permutations from an array of words. I had this question in an interview. Given an array of words ['cat', 'dog', 'tac', 'god', 'act'], return an array with all the anagrams grouped together. Makes sure the anagrams are unique.
var arr = ['cat', 'dog', 'tac', 'god', 'act'];
var allAnagrams = function(arr) {
var anagrams = {};
arr.forEach(function(str) {
var recurse = function(ana, str) {
if (str === '')
anagrams[ana] = 1;
for (var i = 0; i < str.length; i++)
recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
};
recurse('', str);
});
return Object.keys(anagrams);
}
console.log(allAnagrams(arr));
//["cat", "cta", "act", "atc", "tca", "tac", "dog", "dgo", "odg", "ogd", "gdo", "god"]
Assuming a large string to search, you could use a regular expression
to examine a set of possibles that first matches the letters and the total number of letters,
and return the matches that use the same letter set as the pattern.
//(case-insensitive)
function lettersets(str, pat){
var A= [], M, tem,
rx= RegExp('\\b(['+pat+']{'+pat.length+'})\\b', 'gi'),
pattern= pat.toLowerCase().split('').sort().join('');
while((M= rx.exec(str))!= null){
tem= M[1].toLowerCase().split('').sort();
if(tem.join('')=== pattern) A.push(M[1]);
};
return A;
}
lettersets(s, 'the').sort();
function swap(a, b, str) {
if (a == b)
str = str;
else {
str = str.split("");
var temp = str[a];
str[a] = str[b];
str[b] = temp;
str = str.join("");
}
}
function anagram(a1, b1, ar) {
if (a1 == b1)
document.write(ar + "<br/>");
else
for (i = a1; i < b1; i++) {
swap(a1, b1, ar);
anagram((a1) ++, b1, ar);
swap(a1, b1, ar);
}
}
Well there isnt any built in function in js(i dont believe it to be in any coding language)......and anyways this is the fully functioning program, it omits any repetitions and also displays the number of permutations.....
var n=0;
var counter=0;
var storarr=new Array();
function swap(a,b,str) { //swaps the terms str[a] and str[b] and returns the final str
str = str.split("");
var temp = str[a];
str[a] = str[b];
str[b] = temp;
return str.join("");
}
function anagram(_a,_b,ar) { //actual function which produces the anagrams
if(_a == _b) {
storarr[n]=ar;
n++;
counter++;
}
else {
for(var i= _a;i<= _b;i++) {
ar=swap(_a,i,ar);
anagram(_a+1,_b,ar);
ar=swap(_a,i,ar);
}
}
}
function factorial(a) { //return a!
var x=1;
for(var i=1;i<=a;i++)
x=x*i;
return x;
}
var strl=prompt("Enter String:","");
var l=strl.length;
anagram(0,l-1,strl);
storarr.sort(); //sorts the storarr alphabetically
var storlen=storarr.length;
var cai=0;
var counterarr = new Array();
strl.split("");
for(var i=0;i<l;i=i+c) { //determines the number of times a term is repeating
var c=1;
for(var j=i+1;j<l;j++) {
if(strl[i]==strl[j])
c++;
}
counterarr[cai]=c;
cai++;
}
var yellow=1;
for(var i=0;i<counterarr.length;i++) { //multiplies the terms of the counter array
yellow=yellow*factorial(counterarr[i]);
}
counter=counter/yellow;
document.write("Count : " + counter + "<br />");
for(var i=0;i<storlen;i=i+yellow) { //prints the non-flagged terms in storarr
document.write(storarr[i] + "<br />");
}
strl.join("");
<pre>
<script>
var count = 0;
var duplicate = false;
function FindAllPermutations(str, index) {
for (var i = index; i < str.length; i++) {
var newstr;
if (index == i) newstr = str;
else newstr = SwapLetters(str, index, i);
if (!duplicate) {
count++;
document.write(newstr + "\n");
if (i == index) duplicate = true;
} else if (i != index) duplicate = false;
FindAllPermutations(newstr, index + 1);
}
}
function SwapLetters(str, index1, index2) {
if (index1 == index2) return str;
str = str.split("");
var temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
return str.join("");
}
FindAllPermutations("ABCD", 0); // will output all 24 permutations with no duplicates
document.write("Count: " + count);
</script>