Find the Longest Word in a String javascript - javascript

My code was work well with string like "The quick brown fox jumped over the lazy dog".
But not work with string like "Google do a barrel roll".
It says problem is "TypeError undefined is not an object(evaluating 'Astr[i].length') ".
function findLongestWord(str) {
var Astr = str.split(" ");
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i =1; i < t;i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord("Google do a barrel roll");

Here is one way of improving your function:
var str = 'Google do a barrel roll';
function findLongestWord(str) {
var Astr = str.split(' ');
if (!Astr.length) {
throw new Error('findLongestWord(): no words in str');
}
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i = 0; i < Al; i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord(str);
//=> 6
You can also do something like this (which is a little easier to understand):
str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '');
//=> Google

you have problem with the variables in your 'for' loop.
As you can see, you split the array and get the length of the first member in the array
So basicly you get the first word length instead of the word count
var Astr = str.split(" ");
var t = Astr[0].length;
Here you can see that you use 't' (the first word length) as your loop bounds.
for(var i =1; i < t;i++)
Keep your code simple & readable this way it will be maintainable.
function findLongestWord(str) {
var words = str.split(" ");
var words_count = words.length;
var longest_word_length = 0;
for(var i = 0; i < words_count; i++){
if(longest_word_length < words[i].length){
longest_word_length = words[i].length;
}
}
return longest_word_length;
}
findLongestWord("Google do a barrel roll");
Note that you always can use short-hand functions for that
function findLongestWord(str) {
return str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '').length;
}
findLongestWord("Google do a barrel roll");

function findLongestWord(str)
{var arr=[];
arr=str.split(' ');
arr=arr.sort(function(a,b)
{
return b.length-a.length; /*sorting the array in decending order of
lengths of each word*/
});
var st=arr[0]; /* obviously the first element of the array will
have longest length.*/
return st.length;
}
findLongestWord("Google do a barrel roll");

Related

Doubling each letter in a String in js

I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));

String with the highest frequency of recurring letters in a word

This is a challenge for coderbyte I thought I'd try to do it using a different method for solving it than loops, objects. It passed but it isn't perfect. The directions for the challenge are:
Have the function LetterCountI(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: "Today, is the greatest day ever!" should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's. If there are no words with repeating letters return -1. Words will be separated by spaces.
function LetterCountI(str){
var wordsAndLetters = {};
var count = 0;
var finalword;
str = str.split(" ");
for(var i = 0; i < str.length; i++){
wordsAndLetters[str[i]] = wordsAndLetters[str[i]] || 0;
}
function countWordLetters(strs){
strs = strs.split("");
var lettercount = {};
for(var i = 0; i <strs.length; i++){
lettercount[strs[i]] = lettercount[strs[i]] || 0;
lettercount[strs[i]]++;
}
return lettercount;
}
for(var words in wordsAndLetters){
wordsAndLetters[words] = countWordLetters(words);
var highestLetterFrequency = wordsAndLetters[words];
for(var values in highestLetterFrequency){
if(highestLetterFrequency[values] > count){
count = highestLetterFrequency[values];
finalword = words;
}
if(count !== 1){
return finalword;
}
}
}
return -1;
}
LetterCountI("today is the greatest day ever!");
Sorry if some of the variable names are confusing I've been up for far too long trying to figure out what I did wrong. If you use the parameters at the bottom of the code it returns 'greatest' like it should however change the parameters to
LetterCountI("toddday is the greatttttest day ever!");
and it logs 'toddday' when it should log 'greatttttest'. Is my code completely wrong? I realize if the parameters were ("caatt dooog") it should log 'caatt' since there are 4 recurring letters but I'm not worried about that I just am concerned about it finding the most recurrence of one letter(but by all means if you have a solution I would like to hear it!). Any changes to the variables if needed to make this code more readable would be appreciated!
The problem with your code is the positioning of the following section of code:
if(count !== 1){
return finalword;
}
Move it from where it currently is to just before the return -1, like so:
for(var words in wordsAndLetters){
wordsAndLetters[words] = countWordLetters(words);
var highestLetterFrequency = wordsAndLetters[words];
for(var values in highestLetterFrequency){
if(highestLetterFrequency[values] > count){
count = highestLetterFrequency[values];
finalword = words;
}
}
}
if(count !== 1){
return finalword;
}
return -1;
The problem with your original code is that your were returning the first word that had repeating characters, which meant your code didn't get far enough to check if any subsequent words had more repeating characters.
Also, just for fun, here is my alternative solution.
Here you go
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
function LetterCountI(str){
var temp = str.split(" ");
var final = '', weight = 0;
for(var i = 0; i < temp.length; ++i) {
var word = temp[i].split("");
if(word.getUnique().length < word.length) {
var diff = word.length - word.getUnique().length;
if(diff > weight){
weight = diff;
final = temp[i];
}
}
}
return final;
}
console.log(LetterCountI("Catt dooog"));
console.log(LetterCountI("toddday is the greatttttest day ever!"));
Viva LinQ !!!!!
var resultPerWord = new Dictionary<string, int>();
var S = "toddday is the greatttttest day ever!";
foreach(var s in S.Split(' '))
{
var theArray =
from w in s
group w by w into g
orderby g.Count() descending
select new { Letter = g.Key, Occurrence = g.Count() };
resultPerWord.Add(s, theArray.First().Occurrence);
}
var r = "-1";
if (resultPerWord.Any(x => x.Value >1))
{
r = resultPerWord.OrderByDescending(x => x.Value).First().Key;
}

Javascript: find longest word in a string

function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
When I call longestWord("Pride and Prejudice"), it returns 'Pride' and not 'Prejudice' which is the longest word... why? I checked some other similar questions, but the solutions looked a lot like my code.
That's because you're not comparing all the items in the array, you leave out the last one.
for (var i = 0; i < str.length - 1; i++)
should be
for (var i = 0; i < str.length; i++)
or
for (var i = 0; i <= str.length - 1; i++)
One advantage to taking a functional approach to such problems is that you don't even have to keep count
See MDN Array.reduce for more info. (note: reduce needs shim for IE8)
function longer(champ, contender) {
return (contender.length > champ.length) ? contender : champ;
}
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
console.log(longestWord("The quick brown fox jumped over the lazy dogs"));
Here this is your solution with a forEach, this will help you avoid the error in the future
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
console.log(longestWord("pride and prejudice"));
Your original problem was just the str.length - 1 should have just been str.length, originally you wouldn't have gotten to the last element of the array
You have a -1 in your condition, it never even scans it:
for (var i = 0; i < str.length - 1; i++) {
Should be:
for (var i = 0; i < str.length; i++) {
Demo: http://jsfiddle.net/LfgFk/
The index is going up to str.length -1:
for (var i = 0; i < str.length - 1; i++) {
So the last word is not processed.
Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice"). You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA).
In case you're in doubt, the simplest way to fix it is removing the -1 from the for loop.
for (var i = 0; i < str.length; i++) {
Check a demo with both versions (the problematic and the fixed): link here.
You can simplify your code with a library like Lo-Dash:
function longestWord(string) {
var words = string.split(' ');
return _.max(words, function(word) { return word.length; });
}
ForEach is faster in FF but slower in Chrome,
but for loop with the cached length and function apply/call is quite faster in both FF and chrome.
Hope the below code helps:
function getLongest (arrStr) {
var longest = 0, word;
for(var i=0 , len = arrStr.length ; i < len ; i++){
if(longest < arrStr[i].length) {
longest = arrStr[i].length;
word = arrStr[i];
}
}
return word;
}
function isLongest (str) {
var arrayStr = str.split(' ');
return function(fn) {
return fn.apply(this,[arrayStr]);
}
}
isLongest("hello aaaaaaaaaaaaaaaaaaaaaaaaa bbb")(getLongest); //aaaaaaaaaaaaaaaaaaaaaaaaa
for (var i = 0; i < str.length - 1; i++)
to
for (var i = 0; i <= str.length - 1; i++)
OR
for (var i = 0; i < str.length; i++)
does this solve the problem??
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i <= str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
document.write(longestWord("pride and prejudice"));
I find that the .map method here helps a lot (this is if you want the character count of the word, not the word itself):
function findLongestWord(str) {
var array = str.split(/\s+/);
var wordLength = array.map(function(i) {
return i.length;
});
var largest = Math.max.apply(Math, wordLength);
return largest;
}
I will refer you to this awesome article which defines three ways:
1 - Find the Longest Word With a FOR Loop
function findLongestWord(str) {
var strSplit = str.split(' ');
var longestWord = 0;
for(var i = 0; i < strSplit.length; i++){
if(strSplit[i].length > longestWord){
longestWord = strSplit[i].length;
}
}
return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
2 - Find the Longest Word With the sort() Method
function findLongestWord(str) {
var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
3 - Find the Longest Word With the reduce() Method
function findLongestWord(str) {
var longestWord = str.split(' ').reduce(function(longest, currentWord) {
return currentWord.length > longest.length ? currentWord : longest;
}, "");
return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Of course, it returns the length of the biggest word if you want to get the string, just get rid of the length in return part.
function longestWord(sentence){
var arr = sentence.match(/[a-z]+/gi);
arr.sort(function(a, b){
return b.length - a.length;
});
return arr[0];
}
longestWord('hello man##$%');
// ==> output: hello
function LongestWord(sen) {
// code goes here
const wordsArray = sen.split('').map(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<='9')? c : ' ').join('').split(' ').filter(item => item !== '');
wordsArray.sort((a, b) => a.length < b.length);
return wordsArray[0];
}
Is there a specific reason
for (var i = 0; i < str.length - 1; i++)
isn't
for (var i = 0; i < str.length - 1; i++)
That seems like it could be the cause.
You need to use:
for (var i=0;i<=str.length - 1; i++)
That way it will scan the entire phrase
Thanks everyone, this is the fixed code:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[i].length; j++) {
if (/[a-zA-Z]/.test(str[i][j])) {
checkedLetters += str[i][j];
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
}
return word;
}
This seems to be the easiest way to do this.
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
I would say using the forEach loop is the most understandable version
function longestWord(sen) {
big_word = ""
words = sen.split(" ")
words.forEach(function(word){
if (word.length > big_word.length){
big_word = word
};
});
return big_word
};
I think this is more easy
function findLongestWord(str) {
var longestStr = 0;
for (var x=0;x<str.split(' ').length;x++){
if (longestStr < str.split(' ')[x].length){
longestStr = str.split(' ')[x].length;
}
}
return longestStr;
}
Here is one other way to solve it.
function findLongestWord(str) {
var result = [];
var one = str.split(" ");
for (var i = 0; i < one.length; i++) {
result[i] = one[i].length;
result.reverse().sort(function(a,b) {
return b-a;
});
}
return result[0];
}
Using the sort() method,this sorts the elements of an array by some ordering criterion and then returns the length of the first element of this array and hence the longest word.
function longest(string){
var longestWord = string.split(' ').sort(function(a,b){
return b.length - a.length;
});
return longestWord[0];
}
TRY THIS
function longest(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i <= str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
Another method is by using sort:
function longestWord(string) {
let longest = 0;
let str = str.split(" ").sort((word1,word2)=>{
});
return str[0].length;
}
longestWord('I love Python ')
Code below will find the largest word and its length from a string.
Code is in plain JavaScript and html.
function findLongestWord() {
var str = document.getElementById('inputText').value;
calculateLength(str);
}
function calculateLength(str) {
var substring = str.split(" ");
var minChar = '';
for (var i = 0; i <= substring.length - 1; i++) {
if (substring[i].length >= minChar.length) {
minChar = substring[i];
}
}
document.getElementById('longChar').innerHTML = 'Longest Word: ' + minChar;
document.getElementById('longCharLength').innerHTML = 'Longest Word length: ' + minChar.length;
}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<input type="text" id="inputText"> <br/>
<button onclick=findLongestWord()>Click to find longest word</button> <br/>
<div id="longChar"></div> <br/>
<div id="longCharLength"></div>
</body>
<script src="longestWord.js"></script>
</html>
function findLongestWord(str) {
let stringArray = str.split(" ");
stringArray.sort(function(a, b){
return a.split('').length < b.split('').length;
})
return stringArray[0];
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function sortNumber(a, b) {
return a - b;
}
function findLongestWordLength(str) {
var split = str.split(" ");
var arr=[];
for(var i=0;i<split.length;i++){
arr.push(split[i].length);
}
arr.sort(sortNumber);
console.log(arr[arr.length-1]);
return(arr[arr.length-1]);
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");
const longestWord = string =>
{
stringArray = string.split(' ').sort(
(a,b) => b.length - a.length)
let longestArray= stringArray.filter( word => word.length === stringArray[0].length )
if(longestArray.length === 1){
console.log(longestArray[0])
}
else
{
console.log(longestArray)
}
}
longestWord("Pride and Prejudice")
// My simple solution.
const findLongestWordLength = str => {
let array = str.split(" ");
let longest = 0;
array.map(e => {
if (e.length > longest) {
longest = e.length;
}
})
return longest;
}
Solutions above are incomplete. What if there r 2 or more words that have same length. here is a better solution:
longest = str => {
let words = str.split(" ");
let size = 0;
let max = [""];
for (let i = 0; i < words.length; i++) {
if (words[i].length > size) {
size = words[i].length;
}
if (max[max.length - 1].length < words[i].length) {
max = [];
max.push(words[i]);
} else {
max = [...max, words[i]];
}
}
return max;
};
For error checking in question, refer this answer
Longest word in String
Using for/forEach loop
function longestWord(str){
const words = str.split(' ');
let longWord = "";
words.forEach((word) => {
if(word.length > longWord.length) { longWord = word }
})
return longWord;
}
Using sort
function longestWord(str) {
return str.split(' ')
.sort((a, b) => b.length - a.length)[0];
}
Using reduce
function longestWord(str){
return str.split(' ')
.reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}
// for loop
function longestWord1(str){
const words = str.split(' ');
let longWord = "";
words.forEach((word) => {
if(word.length > longWord.length) { longWord = word }
})
return longWord;
}
// sort
function longestWord2(str) {
return str.split(' ').sort((a, b) => b.length - a.length)[0];
}
// reduce
function longestWord3(str){
return str.split(' ').reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}
let text;
text = "What if we try a super-long word such as otorhinolaryngology";
console.log(longestWord1(text));//=> "otorhinolaryngology"
text = "";
console.log(longestWord2(text));//=> ""
text = "What "
console.log(longestWord3(text));//=> "What"
text = "What is pen?"
console.log(longestWord1(text));//=> "What"
text = "three four five six twenty one"
console.log(longestWord2(text));//=> "twenty"
text = ("The quick brown fox jumped over the lazy dog")
console.log(longestWord3(text));//=> "jumped"

Find the characters in a string which are not duplicated

I have to make a function in JavaScript that removes all duplicated letters in a string. So far I've been able to do this: If I have the word "anaconda" it shows me as a result "anaconda" when it should show "cod". Here is my code:
function find_unique_characters( string ){
var unique='';
for(var i=0; i<string.length; i++){
if(unique.indexOf(string[i])==-1){
unique += string[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
We can also now clean things up using filter method:
function removeDuplicateCharacters(string) {
return string
.split('')
.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
})
.join('');
}
console.log(removeDuplicateCharacters('baraban'));
Working example:
function find_unique_characters(str) {
var unique = '';
for (var i = 0; i < str.length; i++) {
if (str.lastIndexOf(str[i]) == str.indexOf(str[i])) {
unique += str[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
console.log(find_unique_characters('anaconda'));
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. but obviously you know that already, otherwise there wouldn't be a question ;-)
Just wanted to add my solution for fun:
function removeDoubles(string) {
var mapping = {};
var newString = '';
for (var i = 0; i < string.length; i++) {
if (!(string[i] in mapping)) {
newString += string[i];
mapping[string[i]] = true;
}
}
return newString;
}
With lodash:
_.uniq('baraban').join(''); // returns 'barn'
You can put character as parameter which want to remove as unique like this
function find_unique_characters(str, char){
return [...new Set(str.split(char))].join(char);
}
function find_unique_characters(str, char){
return [...new Set(str.split(char))].join(char);
}
let result = find_unique_characters("aaaha ok yet?", "a");
console.log(result);
//One simple way to remove redundecy of Char in String
var char = "aaavsvvssff"; //Input string
var rst=char.charAt(0);
for(var i=1;i<char.length;i++){
var isExist = rst.search(char.charAt(i));
isExist >=0 ?0:(rst += char.charAt(i) );
}
console.log(JSON.stringify(rst)); //output string : avsf
For strings (in one line)
removeDuplicatesStr = str => [...new Set(str)].join('');
For arrays (in one line)
removeDuplicatesArr = arr => [...new Set(arr)]
Using Set:
removeDuplicates = str => [...new Set(str)].join('');
Thanks to David comment below.
DEMO
function find_unique_characters( string ){
unique=[];
while(string.length>0){
var char = string.charAt(0);
var re = new RegExp(char,"g");
if (string.match(re).length===1) unique.push(char);
string=string.replace(re,"");
}
return unique.join("");
}
console.log(find_unique_characters('baraban')); // rn
console.log(find_unique_characters('anaconda')); //cod
​
var str = 'anaconda'.split('');
var rmDup = str.filter(function(val, i, str){
return str.lastIndexOf(val) === str.indexOf(val);
});
console.log(rmDup); //prints ["c", "o", "d"]
Please verify here: https://jsfiddle.net/jmgy8eg9/1/
Using Set() and destructuring twice is shorter:
const str = 'aaaaaaaabbbbbbbbbbbbbcdeeeeefggggg';
const unique = [...new Set([...str])].join('');
console.log(unique);
Yet another way to remove all letters that appear more than once:
function find_unique_characters( string ) {
var mapping = {};
for(var i = 0; i < string.length; i++) {
var letter = string[i].toString();
mapping[letter] = mapping[letter] + 1 || 1;
}
var unique = '';
for (var letter in mapping) {
if (mapping[letter] === 1)
unique += letter;
}
return unique;
}
Live test case.
Explanation: you loop once over all the characters in the string, mapping each character to the amount of times it occurred in the string. Then you iterate over the items (letters that appeared in the string) and pick only those which appeared only once.
function removeDup(str) {
var arOut = [];
for (var i=0; i < str.length; i++) {
var c = str.charAt(i);
if (c === '_') continue;
if (str.indexOf(c, i+1) === -1) {
arOut.push(c);
}
else {
var rx = new RegExp(c, "g");
str = str.replace(rx, '_');
}
}
return arOut.join('');
}
I have FF/Chrome, on which this works:
var h={};
"anaconda".split("").
map(function(c){h[c] |= 0; h[c]++; return c}).
filter(function(c){return h[c] == 1}).
join("")
Which you can reuse if you write a function like:
function nonRepeaters(s) {
var h={};
return s.split("").
map(function(c){h[c] |= 0; h[c]++; return c}).
filter(function(c){return h[c] == 1}).
join("");
}
For older browsers that lack map, filter etc, I'm guessing that it could be emulated by jQuery or prototype...
This code worked for me on removing duplicate(repeated) characters from a string (even if its words separated by space)
Link: Working Sample JSFiddle
/* This assumes you have trim the string and checked if it empty */
function RemoveDuplicateChars(str) {
var curr_index = 0;
var curr_char;
var strSplit;
var found_first;
while (curr_char != '') {
curr_char = str.charAt(curr_index);
/* Ignore spaces */
if (curr_char == ' ') {
curr_index++;
continue;
}
strSplit = str.split('');
found_first = false;
for (var i=0;i<strSplit.length;i++) {
if(str.charAt(i) == curr_char && !found_first)
found_first = true;
else if (str.charAt(i) == curr_char && found_first) {
/* Remove it from the string */
str = setCharAt(str,i,'');
}
}
curr_index++;
}
return str;
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
Here's what I used - haven't tested it for spaces or special characters, but should work fine for pure strings:
function uniquereduce(instring){
outstring = ''
instringarray = instring.split('')
used = {}
for (var i = 0; i < instringarray.length; i++) {
if(!used[instringarray[i]]){
used[instringarray[i]] = true
outstring += instringarray[i]
}
}
return outstring
}
Just came across a similar issue (finding the duplicates). Essentially, use a hash to keep track of the character occurrence counts, and build a new string with the "one-hit wonders":
function oneHitWonders(input) {
var a = input.split('');
var l = a.length;
var i = 0;
var h = {};
var r = "";
while (i < l) {
h[a[i]] = (h[a[i]] || 0) + 1;
i += 1;
}
for (var c in h) {
if (h[c] === 1) {
r += c;
}
}
return r;
}
Usage:
var a = "anaconda";
var b = oneHitWonders(a); // b === "cod"
Try this code, it works :)
var str="anaconda";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){
return obj;
}
}
).join("");
//output: "cod"
This should work using Regex ;
NOTE: Actually, i dont know how this regex works ,but i knew its 'shorthand' ,
so,i would have Explain to you better about meaning of this /(.+)(?=.*?\1)/g;.
this regex only return to me the duplicated character in an array ,so i looped through it to got the length of the repeated characters .but this does not work for a special characters like "#" "_" "-", but its give you expected result ; including those special characters if any
function removeDuplicates(str){
var REPEATED_CHARS_REGEX = /(.+)(?=.*?\1)/g;
var res = str.match(REPEATED_CHARS_REGEX);
var word = res.slice(0,1);
var raw = res.slice(1);
var together = new String (word+raw);
var fer = together.toString();
var length = fer.length;
// my sorted duplicate;
var result = '';
for(var i = 0; i < str.length; i++) {
if(result.indexOf(str[i]) < 0) {
result += str[i];
}
}
return {uniques: result,duplicates: length};
} removeDuplicates('anaconda')
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
I have 3 loopless, one-line approaches to this.
Approach 1 - removes duplicates, and preserves original character order:
var str = "anaconda";
var newstr = str.replace(new RegExp("[^"+str.split("").sort().join("").replace(/(.)\1+/g, "").replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")+"]","g"),"");
//cod
Approach 2 - removes duplicates but does NOT preserve character order, but may be faster than Approach 1 because it uses less Regular Expressions:
var str = "anaconda";
var newstr = str.split("").sort().join("").replace(/(.)\1+/g, "");
//cdo
Approach 3 - removes duplicates, but keeps the unique values (also does not preserve character order):
var str = "anaconda";
var newstr = str.split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
//acdno
function removeduplicate(str) {
let map = new Map();
// n
for (let i = 0; i < str.length; i++) {
if (map.has(str[i])) {
map.set(str[i], map.get(str[i]) + 1);
} else {
map.set(str[i], 1);
}
}
let res = '';
for (let i = 0; i < str.length; i++) {
if (map.get(str[i]) === 1) {
res += str[i];
}
}
// o (2n) - > O(n)
// space o(n)
return res;
}
If you want your function to just return you a unique set of characters in your argument, this piece of code might come in handy.
Here, you can also check for non-unique values which are being recorded in 'nonUnique' titled array:
function remDups(str){
if(!str.length)
return '';
var obj = {};
var unique = [];
var notUnique = [];
for(var i = 0; i < str.length; i++){
obj[str[i]] = (obj[str[i]] || 0) + 1;
}
Object.keys(obj).filter(function(el,ind){
if(obj[el] === 1){
unique+=el;
}
else if(obj[el] > 1){
notUnique+=el;
}
});
return unique;
}
console.log(remDups('anaconda')); //prints 'cod'
If you want to return the set of characters with their just one-time occurrences in the passed string, following piece of code might come in handy:
function remDups(str){
if(!str.length)
return '';
var s = str.split('');
var obj = {};
for(var i = 0; i < s.length; i++){
obj[s[i]] = (obj[s[i]] || 0) + 1;
}
return Object.keys(obj).join('');
}
console.log(remDups('anaconda')); //prints 'ancod'
function removeDuplicates(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 +=char;
}
}
return result;
}
console.log(("anaconda").split('').sort().join('').replace(/(.)\1+/g, ""));
By this, you can do it in one line.
output: 'cdo'
function removeDuplicates(string){
return string.split('').filter((item, pos, self)=> self.indexOf(item) == pos).join('');
}
the filter will remove all characters has seen before using the index of item and position of the current element
Method 1 : one Simple way with just includes JS- function
var data = 'sssssddddddddddfffffff';
var ary = [];
var item = '';
for (const index in data) {
if (!ary.includes(data[index])) {
ary[index] = data[index];
item += data[index];
}
}
console.log(item);
Method 2 : Yes we can make this possible without using JavaScript function :
var name = 'sssssddddddddddfffffff';
let i = 0;
let newarry = [];
for (let singlestr of name) {
newarry[i] = singlestr;
i++;
}
// now we have new Array and length of string
length = i;
function getLocation(recArray, item, arrayLength) {
firstLaction = -1;
for (let i = 0; i < arrayLength; i++) {
if (recArray[i] === item) {
firstLaction = i;
break;
}
}
return firstLaction;
}
let finalString = '';
for (let b = 0; b < length; b++) {
const result = getLocation(newarry, newarry[b], length);
if (result === b) {
finalString += newarry[b];
}
}
console.log(finalString); // sdf
// Try this way
const str = 'anaconda';
const printUniqueChar = str => {
const strArr = str.split("");
const uniqueArray = strArr.filter(el => {
return strArr.indexOf(el) === strArr.lastIndexOf(el);
});
return uniqueArray.join("");
};
console.log(printUniqueChar(str)); // output-> cod
function RemDuplchar(str)
{
var index={},uniq='',i=0;
while(i<str.length)
{
if (!index[str[i]])
{
index[str[i]]=true;
uniq=uniq+str[i];
}
i++;
}
return uniq;
}
We can remove the duplicate or similar elements in string using for loop and extracting string methods like slice, substring, substr
Example if you want to remove duplicate elements such as aababbafabbb:
var data = document.getElementById("id").value
for(var i = 0; i < data.length; i++)
{
for(var j = i + 1; j < data.length; j++)
{
if(data.charAt(i)==data.charAt(j))
{
data = data.substring(0, j) + data.substring(j + 1);
j = j - 1;
console.log(data);
}
}
}
Please let me know if you want some additional information.

What's the most efficient algorithm to find the indexes of multiple characters inside a string (javascript)?

I'm looking for the fastest method I can use to search a body of text for the indexes of multiple characters.
For example:
searchString = 'abcdefabcdef';
searchChars = ['a','b'];
// returns {'a':[0,6], 'b':[1,7]}
You should be able to use a regular expression to find all occurances of each character. Something like:
function findIndexes(find, str) {
var output = {};
for (var i = 0; i < find.length; i++) {
var m = [];
var r = new RegExp('.*?' + find[i], 'g');
var ofs = -1;
while ((x = r.exec(str)) != null) {
ofs += x[0].length;
m.push(ofs);
}
output[find[i]] = m;
}
return output;
}
Edit:
Did some changes, and now it works. :) However, as Javascript doesn't have a matches method to get all matches at once, it's not really any improvment over using indexOf... :P
Edit 2:
However, you can use a regular expression to find any of the characters, so you only need to loop the string once instead of once for each character. :)
function findIndexes(find, str) {
var output = {};
for (var i = 0; i < find.length; i++) output[find[i]] = [];
var r = new RegExp('.*?[' + find.join('') + ']', 'g');
var ofs = -1;
while ((x = r.exec(str)) != null) {
ofs += x[0].length;
output[x[0].substr(x[0].length-1,1)].push(ofs);
}
return output;
}
Assuming few letters to search for and many letters to search against (i.e. low number of letter, long strings), the latter is the most efficient, since you only go through the string once, and then test each letter.
The other one goes through the string as many times as there are letters to search for.
After timing a few single pass algorithms and Guffa's regex, I ended up going with this:
function findIndexesMultiPass(str,find) {
var x, output = {};
for (var i = 0; i < find.length; i++) {
output[find[i]] = [];
x = 0;
while ((x = str.indexOf(find[i], x)) > -1) {
output[find[i]].push(x++);
}
}
return output;
}
var searchString = "abcd abcd abcd";
var searchChars = ['a', 'b'];
var result = findIndexesMultiPass(searchString, searchChars);
// {'a':[0,5,10], 'b':[1,6,11]}
This turned out to be pretty slow:
function findIndexesOnePass(str,find) {
var output = {};
for (var i = 0; i < find.length; i++) {
output[find[i]] = [];
}
for (var i = 0; i < str.length; i++) {
var currentChar = str.charAt(i);
if (output[currentChar] !== undefined) {
output[currentChar].push(i);
}
}
return output;
}
var searchString = "abcd abcd abcd";
var searchChars = ['a', 'b'];
var result = findIndexesOnePass(searchString, searchChars);
// {'a':[0,5,10], 'b':[1,6,11]}
Rough times (indexes of 3 characters)
Google Chrome (Mac)
findIndexesMultiPass: 44ms
findIndexesOnePass: 799ms
findIndexesRegEx: 95ms
Safari
findIndexesMultiPass: 48ms
findIndexesOnePass: 325ms
findIndexesRegEx: 293ms
Firefox
findIndexesMultiPass: 56ms
findIndexesOnePass: 369ms
findIndexesRegEx: 786ms

Categories