Returning subset using loop - javascript

I wrote this code
function sub (str, start, end) {
var newstr = ''
for(var i = 0; i < str.length; i++) {
if(i >= start && i < end) {
newstr += str[i]
}
}
return newstr
}
I expect the output of ('abcd',0,10) to be 'ab', but the actual output is 'a'

If your goal is to get a function which takes starting and ending index to return substring, then you can use slice function on Strings.
var word = 'ascsjdksjdnc';
word.slice(2, 4);
// Output: 'cs'

Related

Write a function that returns a subset of a string between one index and another without using built-in function

Write a function that returns a subset of a string between one index and another. Without using any built-in function: substr, substring, slice, splice...
Hi guys, can you help me with this, the code went wrong and i don't know how to fix it.Thanks
Example (("abcd",1,10) return "bcd")
I alter it thanks to you guys. But it still missing something, like it only work if the substring is the start of the string.
function func3(str, indexStart, indexEnd) {
var result = "";
for (var i = indexStart; i < indexEnd && i < str.length; i++) {
var x = str.charAt(i);
if (indexEnd > i > indexStart) {
var y = str.charAt(i);
}
}
result += x + y
}
return result
}
console.log(func3('abcdxyz', 1, 10));
You could check if i is not only smaller than the given end, but also if the length is smaller than the length of the string.
function func3(str, indexStart, indexEnd) {
var result = "";
for (var i = indexStart; i < indexEnd && i < str.length; i++) {
result += str[i];
}
return result;
}
console.log(func3("abcd", 1, 10));
An even shorter approach by taking the minimum length in advance.
function func3(str, indexStart, indexEnd) {
var result = "",
i,
l = Math.min(indexEnd, str.length);
for (i = indexStart; i < l; i++) {
result += str[i];
}
return result;
}
console.log(func3("abcd", 1, 10));
var result = "";
for (var i=indexStart; i < indexEnd; i++){
result += str.charAt(i);
}
return result
function func3(str, indexStart, indexEnd) {
var result="";
for (var i=Math.max(0, indexStart); i<=indexEnd || i>str.lengths; i++) {
result += str.charAt(i);
}
return result;
}
console.log(func3("abcd", 1, 10));
console.log(func3("abcd", -1, 10));
console.log(func3("abcd", 2, 2));
console.log(func3("abcd", 7, 10));
If prototype functions ain't your thing, this may be what you are looking for:
function charBetween(str, start, end) {
let res = '';
if (start > end) return res;
while (str[start] !== undefined && start <= end) {
res += str[start];
start++;
}
return res;
}
console.log(charBetween("This is a test.", 9, 100));
I have also added a prototype function to String's if you would like to use it. By doing this you may call this function like so:
String.prototype.charBetween = function(start, end) {
'use strict'; // `this` refers to an object without strict set.
let res = '';
if (start > end) return res;
while (this[start] !== undefined && start <= end) {
res += this[start];
start++;
}
return res;
}
console.log("This is a test.".charBetween(9, 100));
Hope this helps,
You are declaring two variables x and y and y may not be present every time.
function func3(str,indexStart,indexEnd){
var result = "";
var x;
for (var i=indexStart; i < indexEnd; i++){
x = str.charAt(i);
if (indexEnd>i && i > indexStart){
x =str.charAt(i);
}
else if (i>indexEnd){
break;
}
result += x
}
return result
}
console.log(func3("abcd",1,3))
A simpler way is to get the the min value out of length of string an end index. And then loop only upto that.
function func3(str,indexStart,indexEnd){
var result = "";
let len = Math.min(str.length,indexEnd)
for (var i=indexStart; i < len; i++){
result += str[i];
}
return result
}
console.log(func3("abcd",1,10))

Count repeated letters in a string

I'm stuck with the following problem:
I need to find repeated characters in a string.
Basically what I want is regular expression that will match like that
hello - ["ll"];
here - ["ee"];
happiness - ["pp","ss"];
pupil - ["pp"];
I have the one that matches consecutive repeated characters
/([a-z])\1+/g
Also the one that will match repeated chars and everything between them like this one
/([a-z])(?:.*)\1+/g
But cant figure out the correct one.
You can use
([a-zA-Z]).*(\1)
Demo regex
Since you have clarified that you are looking for a solution that will handle something other than double letters in a string, you should use a non-regex approach such as:
Build an associative array with the count of the characters in the string:
var obj={}
var repeats=[];
str='banana'
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
}
console.log(obj)
Prints
{ b: 1, a: 3, n: 2 }
Then build an array of your specifications:
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key]>1) {
repeats.push(new Array( obj[key]+ 1 ).join( key ));
}
}
console.log(repeats)
Prints:
[ 'aaa', 'nn' ]
This method also works well!!
let myString = 'abababc';
let result = {};
for (let str of myString) {
result[str] = result.hasOwnProperty(str) ? result[str] + 1 : 1;
}
console.log(result);
The result will be like this {a: 3, b: 3, c: 1}
For your scenario you second solution seems better. You can get the second letter by other capture group
Regex you be (it is your 2nd RegEx with more one capture group):
/([a-z])(?:.*)(\1)+/g
var re = /([a-z])(?:.*)(\1)+/g;
var str = ['hello', 'here', 'happiness', 'pupil'];
var m;
var result = new Array();
for(var i = 0; i < str.length; i++) {
result[i] = str[i] + "->";
while ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
result[i] += m[1];
result[i] += m[2] + ",";
}
}
document.getElementById("results").innerHTML = result.join("</br>");
<div id="results"></div>
var obj = {};
var str = "this is my string";
for (var i = 97; i < 97 + 26; i++)
obj[String.fromCharCode(i)] = 0;
for (var i = 0; i < str.length; i++) {
obj[str.charAt(i).toLowerCase()]++;
}
From there you can say obj["a"] to get the number of occurrences for any particular letter.
More complicated than a RegExp solution, however it properly handles banana and assassin, where there are two overlapping groups of characters.
This does make use of array.map, array.filter, and array.reduce, which means this exact solution doesn't support <=IE8, however it can be polyfilled quite easily.
function findDuplicateCharacters(input) {
// Split the string and count the occurrences of each character
var count = input.split('').reduce(function(countMap, word) {
countMap[word] = ++countMap[word] || 1;
return countMap;
}, {});
// Get the letters that were found, and filter out any that only appear once.
var matches = Object.keys(count)
.filter(function (key) { return (count[key] > 1); })
// Then map it and create a string with the correct length, filled with that letter.
.map(function (key) {
return new Array(count[key] + 1).join(key);
});
return matches;
}
var results = ['hello', 'here', 'happiness', 'pupil', 'banana'].map(findDuplicateCharacters);
document.getElementById("results").innerHTML = results.join('<br />');
<div id="results"></div>
var re = /([a-z])(?:.*)(\1)+/g;
var str = ['aaaccbcdd'];
var m;
var result = new Array();
for(var i = 0; i < str.length; i++) {
result[i] = str[i] + "->";
while ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
result[i] += m[1];
result[i] += m[2] + ",";
}
}
document.getElementById("results").innerHTML = result.join("</br>");
<div id="results"></div>
function charCount(str){
let arr = str.split('');
return arr.reduce((a,p)=>{
a[p] = a[p] ? (a[p]+1) : 1;
return a;
},{});
};
//Try this method
const countRepeatChar = (str) => {
let obj = {};
if (str) {
for (let i = 0; i < str.length; i++) {
if (obj[str[i]]) {
obj[str[i]] += obj[str[i]];
} else {
obj[str[i]] = 1;
}
}
console.log(obj);
}
};
countRepeatChar("aabcddeee");

return the first non repeating character in a string in javascript

So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.
The problem is I have an arbitrary string that I would like to return the first non repeating character. EX: 'aba' -> would return b
'aabcbd' -> would return c.
This is what I have so far, just a simple for loop to start.
var someString = 'aabcbd';
var firstNonRepeatedCharacter = function(string) {
for(var i = 0; i < someString.length; i++){
}
};
http://jsfiddle.net/w7F87/
Not sure where to go from here
You can use the indexOf method to find the non repeating character. If you look for the character in the string, it will be the first one found, and you won't find another after it:
function firstNonRepeatedCharacter(string) {
for (var i = 0; i < string.length; i++) {
var c = string.charAt(i);
if (string.indexOf(c) == i && string.indexOf(c, i + 1) == -1) {
return c;
}
}
return null;
}
Demo: http://jsfiddle.net/Guffa/Se4dD/
If you're looking for the first occurrence of a letter that only occurs once, I would use another data structure to keep track of how many times each letter has been seen. This would let you do it with an O(n) rather than an O(n2) solution, except that n in this case is the larger of the difference between the smallest and largest character code or the length of the string and so not directly comparable.
Note: an earlier version of this used for-in - which in practice turns out to be incredibly slow. I've updated it to use the character codes as indexes to keep the look up as fast as possible. What we really need is a hash table but given the small values of N and the small, relative speed up, it's probably not worth it for this problem. In fact, you should prefer #Guffa's solution. I'm including mine only because I ended up learning a lot from it.
function firstNonRepeatedCharacter(string) {
var counts = {};
var i, minCode = 999999, maxCode = -1;
for (i = 0; i < string.length; ++i) {
var letter = string.charAt(i);
var letterCode = string.charCodeAt(i);
if (letterCode < minCode) {
minCode = letterCode;
}
if (letterCode > maxCode) {
maxCode = letterCode;
}
var count = counts[letterCode];
if (count) {
count.count = count.count + 1;
}
else {
counts[letterCode] = { letter: letter, count: 1, index: i };
}
}
var smallestIndex = string.length;
for (i = minCode; i <= maxCode; ++i) {
var count = counts[i];
if (count && count.count === 1 && count.index < smallestIndex) {
smallestIndex = count.index;
}
}
return smallestIndex < string.length ? string.charAt(smallestIndex) : '';
}
See fiddle at http://jsfiddle.net/b2dE4/
Also a (slightly different than the comments) performance test at http://jsperf.com/24793051/2
var firstNonRepeatedCharacter = function(string) {
var chars = string.split('');
for (var i = 0; i < string.length; i++) {
if (chars.filter(function(j) {
return j == string.charAt(i);
}).length == 1) return string.charAt(i);
}
};
So we create an array of all the characters, by splitting on anything.
Then, we loop through each character, and we filter the array we created, so we'll get an array of only those characters. If the length is ever 1, we know we have a non-repeated character.
Fiddle: http://jsfiddle.net/2FpZF/
Two further possibilities, using ECMA5 array methods. Will return undefined if none exist.
Javascript
function firstNonRepeatedCharacter(string) {
return string.split('').filter(function (character, index, obj) {
return obj.indexOf(character) === obj.lastIndexOf(character);
}).shift();
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
Or if you want a bit better performance, especially on longer strings.
Javascript
function firstNonRepeatedCharacter(string) {
var first;
string.split('').some(function (character, index, obj) {
if(obj.indexOf(character) === obj.lastIndexOf(character)) {
first = character;
return true;
}
return false;
});
return first;
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
I came accross this while facing similar problem. Let me add my 2 lines.
What I did is a similar to the Guffa's answer. But using both indexOf method and lastIndexOf.
My mehod:
function nonRepeated(str) {
for(let i = 0; i < str.length; i++) {
let j = str.charAt(i)
if (str.indexOf(j) == str.lastIndexOf(j)) {
return j;
}
}
return null;
}
nonRepeated("aabcbd"); //c
Simply, indexOf() gets first occurrence of a character & lastIndexOf() gets the last occurrence. So when the first occurrence is also == the last occurence, it means there's just one the character.
Here's a Solution using Regex to replace all repeating characters and then returning the first character.
function firstNonRepeat(str) {
// Sorting str so that all repeating characters will come together & replacing it with empty string and taking first character using substr.
var rsl = str.split('').sort().join('').replace(/(\w)\1+/g,'').substr(0,1);
if(rsl) return rsl;
else return 'All characters are repeated in ' + str;
}
console.log(firstNonRepeat('aaabcccdeeef'));
console.log(firstNonRepeat('aaacbdcee'));
console.log(firstNonRepeat('aabcbd'));
First of all, start your loop at 1, not 0. There is no point in checking the first character to see if its repeating, obviously it can't be.
Now, within your loop, you have someString[i] and someString[i - 1]. They are the current and previous characters.
if someString[i] === someString[i - 1] then the characters are repeating, if someString[i] !== someString[i - 1] then they are not repeating, so you return someString[i]
I won't write the whole thing out for you, but hopefully the thought process behind this will help
function FirstNotRepeatedChar(str) {
var arr = str.split('');
var result = '';
var ctr = 0;
for (var x = 0; x < arr.length; x++) {
ctr = 0;
for (var y = 0; y < arr.length; y++) {
if (arr[x] === arr[y]) {
ctr+= 1;
}
}
if (ctr < 2) {
result = arr[x];
break;
}
}
return result;
}
console.log(FirstNotRepeatedChar('asif shaik'));
Here's an O(n) solution with 2 ES6 Sets, one tracking all characters that have appeared and one tracking only chars that have appeared once. This solution takes advantage of the insertion order preserved by Set.
const firstNonRepeating = str => {
const set = new Set();
const finalSet = new Set();
str.split('').forEach(char => {
if (set.has(char)) finalSet.delete(char);
else {
set.add(char);
finalSet.add(char);
}
})
const iter = finalSet.values();
return iter.next().value;
}
let arr = [10, 5, 3, 4, 3, 5, 6];
outer:for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length;j++){
if(arr[i]===arr[j+1]){
console.log(arr[i]);
break outer;
}
}
}
//or else you may try this way...
function firstDuplicate(arr) {
let findFirst = new Set()
for (element of arr)
if (findFirst.has(element ))
return element
else
findFirst.add(element )
}
function firstUniqChar(str) {
let myMap = new Map();
for(let i = 0; i < str.length; i++) {
let char = str.charAt(i);
if(!myMap.has(char)) {
myMap.set(char, 0);
}
myMap.set(char, myMap.get(char) + 1 );
}
for(let [key, value] of myMap) {
if(value === 1) {
return key;
}
}
return null;
}
let result = firstUniqChar("caabbdccee");
console.log(result);
You can use Map Object and set key and value, where in value you store the count for that particular character, After that you can iterate over map and check where is value 1 and return that key.
Map Object remembers the original insertion order of the keys.
This solution should works with array with integers and string.
function firstNoneRepeating(list, map = new Map()) {
for (let item of list) {
if (map.has(item)) {
map.set(item, map.get(item) + 1);
} else {
map.set(item, 1);
}
}
for (let [key, value] of map.entries()) {
if (value === 1) {
return key;
}
}
}
console.log(firstNoneRepeating("aabcbd"));
console.log(firstNoneRepeating([5, 2, 3, 4, 2, 6, 7, 1, 2, 3]));
let str='aabcbd'
let ans=''
for (let i=0;i<str.length;i++){
if(str.indexOf(str.charAt(i))===str.lastIndexOf(str.charAt(i))){
ans+=str.charAt(i)
break
}
}
console.log(ans)
Fill an empty array with zeros, with same length as the string array, and tally up how many times they appear through the loop. Grab the first one in the tallied array with a value of 1.
function firstNotRepeatingCharacter(s) {
const array = s.split("");
let scores = new Array(array.length).fill(0);
for (let char of array) {
scores[array.indexOf(char)]++;
}
const singleChar = array[scores.indexOf(1)];
return singleChar ? singleChar : "_"
}
You can iterate through each character to find() the first letter that returns a single match(). This will result in the first non-repeated character in the given string:
const first_nonrepeated_character = string => [...string].find(e => string.match(new RegExp(e, 'g')).length === 1);
const string = 'aabcbd';
console.log(first_nonrepeated_character(string)); // c
Here is my solution which have time complexity of o(n)
function getfirstNonRepeatingCharacterInAString(params) {
let count = {};
for (let i = 0; i < params.length; i++) {
let count1 = 0;
if (!count[params.charAt(i)]) {
count[params.charAt(i)] = count1 + 1;
}
else {
count[params.charAt(i)] = count[params.charAt(i)] + 1;
}
}
for (let key in count) {
if (count[key] === 1) {
return key;
}
}
return null;
}
console.log(getfirstNonRepeatingCharacterInAString("GeeksfoGeeks"));
Here is my solution using forEach and convert the string into an array
function firstNotRepeatingCharacter(s) {
var strArr = s.split("");
var found = "_";
strArr.forEach(function(item, index) {
if (strArr.indexOf(item) == index && strArr.indexOf(item, index + 1) == -1) {
if (found === "_") {
found = item;
}
}
})
return found;
}
firstNotRepeatingCharacter("abacabad")
Here is another approach:
Everytime you find equal chars store it in an array and break out of the loop. If the char is not found in the array then you have your first nonRepeating char
function nonRepeatingChars(value) {
const memory = []
for (let i = 0; i < value.length; i++) {
for (let j = i + 1; j < value.length; j++) {
if (value[i] === value[j]) {
memory.push(value[j])
break;
}
}
if (!memory.some(x => x === value[i])) {
return value[i];
}
}
return "all chars have duplicates";
}
console.log('First non repeating char is:',nonRepeatingChars("esen"))
console.log('First non repeating char is:',nonRepeatingChars("esesn"))
console.log('First non repeating char is:',nonRepeatingChars("eseulsn"))
console.log('First non repeating char is:',nonRepeatingChars("esesnn"))
> var firstNonRepeatedCharacter = function (str){
> for(i=0;i<str.length;i++){
> if(str.indexOf(str.charAt(i)) === str.lastIndexOf(str.charAt(i))){
> console.log(str.charAt(i));
> break;
> } } }
>
> firstNonRepeatedCharacter ("areerak");
you can check below link
https://codepen.io/t3veni/pen/wvvxJzm
Easy way to solve this algorithm, very straight forward.
function firstNonRepeatChar(str){
let map = {};
for(let i=0; i<str.length; i++){
if(Object.keys(map).includes(str[i])){
map[str[i]]++
}
else{
map[str[i]] = 1;
}
}
for(let j=0; j< Object.values(map).length; j++){
if(Object.values(map)[j] == 1){
console.log(Object.keys(map)[j]);
return
}
if (j == Object.values(map).length-1 && Object.values(map)[j] != 1){
console.log('_');
return;
}
else{
continue;
}
}
}
nonRepeat("aaabbcccdeeef");
Here is one other solution just using array, using 26 unique character as length of array:
var firstUniqChar = (function(s) {
var arr = [];
var str = s.toLowerCase();
for(let c of str){
let index = c.charCodeAt(0) - "a".charCodeAt(0);
arr[index]? ++arr[index]: arr[index]=1;
}
for(let c of str){
let index = c.charCodeAt(0) - 97;
if(arr[index] == 1){
return c;
};
}
return -1;
}("aabcbd"));
console.log(firstUniqChar);
We can keep track of frequency of each character of the string in an object.
For example : for "aabcbd" we can store the frequency as
{ "a":2, "b":2, "c":1, "d":1 }
This will take O(n) time.
Then we can traverse over this object and find the first character with frequency 1, which will also take O(n) time. So, the time complexity for this approach will be O(n).
const firstNonRepeating=(str)=>{
const obj={};
str.split("").forEach(item=>{
obj[item]
? obj[item]++
: obj[item]=1;
});
const item = Object.keys(obj).find(key=> obj[key] === 1);
return item;
}
Note: I use ES6 Object.keys method which may not work in older
browsers.
//To find first non repeating letter
//It will check for both upper and lower case
//only use one String.indexOf()
var mystr="ohvhvtccggt";
var checkFirstNonRepeating=function(){
var ele=[];
for(var i=0;i<mystr.length;i++) {
var key=mystr.charAt(i);
if(!ele[key])
ele[key]=0;
ele[key]++;
//Just check for second occurance of character
//no need to use indexOf twice
if(mystr.indexOf(key,i+1)==-1 && ele[key]<2)
return mystr[i];
}
return "All repeating letters";
}
console.log(checkFirstNonRepeating());
/*
Input : "ohvhvtoccggt"
Output : All repeating letters
Input :"oohjtht"
Output :j
*/
I used object to keep track of characters count in a string then return the char that has the fa value of 1. Here is a demo:
function firstNotRepeatingCharacter(s) {
// initialize an empty object to store chars
let seen = {};
let letter = '';
// iterate over each char in a string
// if it is already there increase value by one
// else set the value to 1
for(let char of s){
if (seen[char]){
seen[char] +=1;
} else {
seen[char] = 1;
}
}
// iterate over the new constructed object
// if the value is 1 and the output variable is empty
// return the associated key to the value 1
// else return '_'
for(let v in seen){
while(seen[v] == 1 && letter === ''){
letter += v;
return letter;
}
}
return('_');
}
console.log(firstNotRepeatingCharacter("abacabad"));
console.log(firstNotRepeatingCharacter("cbc"));
console.log(firstNotRepeatingCharacter("bcccccccccccccyb"));
console.log(firstNotRepeatingCharacter("aaa"));
The most satisfactory and easy to understand answer is the following.
function firstNotRepeatingCharacter(s) {
const arr = s.split("");
for(let i = 0; i < arr.length; i++){
let chr = arr[i];
if( arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i])){
return arr[i]
}
}
return "_"
}
Explanation: It loops through all the characters of a string from forward and backward and then compares the values. If the index of both forward and backward search is true then it returns that character.
let str = 'aabbcdd';
let val = str.split('').reduce((a, e)=>{ if(str.indexOf(e) == str.lastIndexOf(e)) {a = e }; return a})
console.log(val); // c
the implementation below has a good time complexity and it accounts for letters with different cases:
steps
must touch every character in the string to know if it's repeated or not
function firstNonRepeatingLetter(wordd) {
const chars = {}
let word = wordd.toLowerCase()
// go through chars
// store chars in hash with values of array storing index of char and true if only 1 encountered so far
for (let i = 0; i < word.length; i += 1) {
let char = word[i]
if (chars[char]) {
chars[char][0] = false
} else {
chars[char] = [true, i]
}
}
let output = ''
let index;
for (let key in chars) {
// return char with true and lowest index
if (chars[key][0]) {
index = index === undefined ? chars[key][1] : index
if (index >= chars[key][1]) {
output = key
}
}
}
return index === undefined ? '' : wordd[index]
}
console.log(firstNonRepeatingLetter('sTreSS')) //T```
The bellow solution is a kind of frequency counter pattern and it will run only one loop, so O(n) will be the time complexity.
function firstNotRepeatingCharacter(str) {
const obj = {};
for (let i = 0, L = str.length; i < L; i++) {
const char = str[i];
obj[char] = obj[char] ? obj[char] + 1 : 1;
}
for (let key of Object.keys(obj)) {
if (obj[key] == 1) {
return key;
}
}
return -1;
}
Here is another solution
function firstNotRepeatingCharacter(s) {
const obj = {};
for (let i of s) {
if(!obj[i]) {
obj[i] = 1;
} else if (obj[i]) {
obj[i] = +obj[i] + 1;
}
}
for (let [key, value] of Object.entries(obj)) {
if(value == 1) return key;
}
return "_"
}
Using below method can achieve first non repeated character
function main(str) {
str = String(str).toLowerCase();
let non_repeated_char = 'N/A';
for (let i = 0; i < str.length; i++) {
let currentChar = str[i];
let repeated_times = String(str).split('').filter(e => e == currentChar).length;
if (repeated_times === 1) {
non_repeated_char = currentChar;
break;
}
}
return non_repeated_char;
};
let Result = main("basketball");
console.log("The Non Repeated char is-->", Result);

Why doesn't .toUpperCase() capitalize str[i]?

Doing a CoderByte challenge:
Using the JavaScript language, have the function LetterChanges(str)
take the str parameter being passed and modify it using the following
algorithm. Replace every letter in the string with the letter
following it in the alphabet (ie. c becomes d, z becomes a). Then
capitalize every vowel in this new string (a, e, i, o, u) and finally
return this modified string.
my solution:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '';
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
newstr[j] = newstr[j].toUpperCase();
}
}
}
return newstr;
}
show(LetterChanges("fun times"));
show(LetterChanges("hello*3"));
The toUpperCase() does not capitalize the vowel I want. It seems correct though. I've even tried something like this:
if (newstr[j] == vowels[i]) {
var toCap = newstr[j].toString();
newstr[j] = toCap.toUpperCase();
}
If you think of a better solution, then please answer the toUpperCase() part and then recommend another solution.
Strings in Javascript are primitive types, not objects.
When you set a property in a primitive type (eg, str[i] = 'a'), Javascript creates a new boxed object for that value, mutates it, then throws it away.
For more details, see the spec.
Instead, you should assemble the new string in a mutable array, then call .join('') to convert it to a string.
You can create another string to build the return string, see bellow a fix in your code
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '',
returnStr = ''; //added to next step
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
returnStr += newstr[j].toUpperCase();
}else{
returnStr += newstr[j];
}
}
}
return returnStr ;
}
You can capitalize the vowels via replace and an uppercasing function:
newstr = newstr.replace(
/[aeiou]/g, // replace all vowels
function(letter) { // called for each match
return letter.toUpperCase();
}
);
Example: http://codepen.io/paulroub/pen/tvhcF
The contents of a string cannot be changed, I.E. they are immutable. Create a new string instead of trying to edit one in-place.
You can make your life easy with the following code
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g,function(x) {
return String.fromCharCode(x.charCodeAt(0)+1); }).replace(/[aeiou]/g,function(y) {
return y.toUpperCase();
});
}

Javascript: Determine if all characters in a string are unique and if not, delete duplicate characters

Have an array set up with a[letter][occurences], but struggling with looping through this array, to check for occurences > 1 and removing the ones that are.
function charFreq(s) {
var i, j;
var a = new Array();
for (j = 0; j < s.length; j++) {
for (i = 0; i < a.length; i++) {
if (a[i][0] == s[j]) {
a[i][1]++;
break;
}
}
if (i == a.length) {
a[i] = [s[j], 1];
}
}
return a[i][0];
}
document.write(charFreq("insert string here"));
This is the mess I've come up with so far:
function check(str) {
var c;
for (c=0; c < a.length; c++) {
if(a[c][1] == 1) {
return true;
break;
} else {
return false;
}
}
}
Using ES6 Set:
// :: unique = Array<any>|string => Array<any>
const unique = xs => [...new Set(xs)]
const dedupe = str => unique(str).join('')
console.log(
unique('foo'), // => ['f', 'o']
dedupe('foo'), // => 'fo'
)
Don't do it that way.
function noDups( s ) {
var chars = {}, rv = '';
for (var i = 0; i < s.length; ++i) {
if (!(s[i] in chars)) {
chars[s[i]] = 1;
rv += s[i];
}
}
return rv;
}
alert(noDups("Shoe fly pie, and apple pan dowdy")); // Shoe flypi,andw
As the length of your string gets longer, your code gets slower by a factor roughly equal to the square of the length of the string.
To delete duplicate characters from an string, you can use the next function that made the user #Cerbrus
function find_unique_characters( string ){
var unique='';
for(var i=0; i<string.length; i++){
if(string.lastIndexOf(string[i]) == string.indexOf(string[i])){
unique += string[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
If you only want to return characters that appear occur once in a
string, check if their last occurrence is at the same position as
their first occurrence.
Your code was returning all characters in the string at least once,
instead of only returning characters that occur no more than once
Link to the thread of stackoverflow Remove duplicate characters from string
​
Here's a quick way:
str = str.split('').filter(function(v,i,self){
return self.indexOf(v) == i;
}).join('');
function RemoveDuplicateLetters(input) {
var result = '', i = 0, char = '';
while (i < input.length) {
char = input.substring(i, i+1);
result += char;
input = input.replace(char,'');
}
return result;
}
I can't see a splice version, so here's one:
function uniqueChars(s) {
var s = s.split('');
var c, chars = {}, i = 0;
while ((c = s[i])) {
c in chars? s.splice(i, 1) : chars[c] = ++i;
}
return s.join('');
}
This assumes only alpha characters, and upper case not equal to lower case.
function uniqueChars(string){
var i= 0, L= string.length, ustring= '', next;
while(i<L){
next= string.charAt(i++);
if(ustring.indexOf(next)== -1) ustring+= next;
}
return ustring.replace(/[^a-zA-Z]/g, '');
}
var s1= 'The quick red fox jumps over the lazy brown dog.';
uniqueChars(s1)
/* returned value: (String)
Thequickrdfoxjmpsvtlazybwng
*/
This returns any unique character-
function uniqueArray(array){
return array.filter(function(itm, i, T){
return T.indexOf(itm)== i;
});
}
var s1= 'The quick red fox jumps over the lazy brown dog.';
uniqueArray(s1.split('')).join('');
/* returned value: (String)
The quickrdfoxjmpsvtlazybwng.
*/

Categories

Resources