The idea is to complete the function and produce a compressed form of the string given. An example would be if the given string was aabbcc then you would get a2b2c2
The issue with the code I created is for some reason it does not work with anything right away that is consecutive or consecutive letters at the end. wwww turns into w4 but aa does not turn into a2 and wuenuneubgnjfniwfibwiebfaaa will not turn into wuenuneubgnjfniwfibwiebfa3
function compressedString(message) {
let out = '';
let count = 1;
for (let i = 0; i < message.length; i++) {
let current = message[i];
let next = message[i + 1];
if (current == next) {
count++;
} else {
out += current + String(count);
count = 1;
}
}
}
I test your algorithm, using given example of your question wuenuneubgnjfniwfibwiebfaaa, the output was w1u1e1n1u1n1e1u1b1g1n1j1f1n1i1w1f1i1b1w1i1e1b1f1a3, what sounds strange for the string compression requirement. When I add a nested condition inner first else in for loop, I acquired the correct result, please view the code bellow and let what do you think about:
function compressedString(message) {
let out = '';
let count = 1;
for (let i = 0; i < message.length; i++) {
let current = message[i];
let next = message[i + 1];
if (current == next) {
count++;
} else {
if(count == 1){
out += current;
}else{
out += current + String(count);
}
count = 1;
}
}
return out;
}
Your issue is the way you are handling it in the end. What happens to the variable next when the loop is on the last iteration? You need to add an extra check on your if.
Try this:
function compressedString(message) {
let out = '';
let count = 1;
for (var i = 0; i < message.length; i++){
let current = message[i];
let next = message[i + 1];
if ( i < message.length-1 && message[i] == next) {
count += 1;
} else {
out += current + String(count);
count = 1;
}
}
return out;
}
so I've been stuck at this problem for a few days:
My Input is this:
"255,255,255,10,251,91,31,4,220,220,220,1"
Its a String with 3 different RGB values, which also come with a number which indicates their quantity going from hightest to lowest.
You could translate the String from above to:
"RED1, GREEN1, BLUE1, QUANTITY1, RED2, GREEN2 ... "
While the 1 stands for the first color and 2 for the second and so on.
What I need to return is the first color without its quantity.
So my output should look like this:
"255,255,255,251,91,31,220,220,220"
I've tried various of things, one is this function:
var firstC, secondC, thirdC;
var pointer = "firstC";
function getEachColorValue(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
endIndex = i;
if (pointer == "firstC") {
firstC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "secondC";
} else if (pointer == "secondC") {
secondC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "thirdC";
} else if (pointer == "thirdC") {
thirdC = color.substring(startIndex, endIndex);
startIndex = endIndex;
pointer = "firstC";
}
}
}
}
This pushes RED1 in firstC, GREEN1 in secondC and BLUE1 in thirdC
I thought about doing that one time, use a function to write firstC, secondC, thirdC into an array, reset them. Then cut col3 into a substring without the first color pallet, then repeat.
// Global variables
var stringHolder;
var newString;
var counter = 0;
var colorSetHT = new Array;
// main
createSubstring(col3);
function createSubstring(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
counter++;
endIndex = i;
}
if (counter == 4) {
stringHolder = color.substring(startIndex, endIndex);
alert(stringHolder);
newString = color.substring(endIndex+1, color.length);
getEachColorValue(stringHolder);
colorSetHT.push(firstC, secondC, thirdC)
colorReset();
counter = 0;
stringHolder = "";
// createSubstring(newString); // ?
}
}
}
I've tried this, but had no luck so far. I even tried to do it recursively.
Im kinda new to Javascript (actually doing it for Extendscript), I think theres a way easier way, working with split/slice but I havent been able to find one yet. I tried to make it as easy and fast to read as possible, please let me know if I can provide any further information, thanks in advance!
Here is how to do it with split.
var input = "255,255,255,10,251,91,31,4,220,220,220,1";
var inputArray = input.split(",");
var outputArray = [];
for(let i = 0;i<inputArray.length;i++)
{
if(i%4 != 3)
{
outputArray.push(inputArray[i]);
}
}
var output = outputArray.join(",");
console.log(output);
Try
let output = input.split(',').filter((x,i)=> i%4-3).join();
let input="255,255,255,10,251,91,31,4,220,220,220,1"
let output = input.split(',').filter((x,i)=> i%4-3).join();
console.log(output);
Use a simple for loop like so:
const str = "255,255,255,10,251,91,31,4,220,220,220,1";
var colors = str.split(",");
var x = Math.floor(colours.length / 4);
while (x--) {
colors.splice((x + 1) * 4 - 1, 1);
}
colors = colors.join(",");
console.log(colors);
ic is my input array and cbList is my internal array that im checking agaist. I want to check the whole array and return the highest value in based on the cbList. I have some ugly code already tried but i dont want to use it, can someone basically make this better and more efficient. I've been searching and cant find anything in my situation.
So basically just want to check ic and if highest pops up, break out and return that value, if no highest is found, then go on to check high value, and so on...
function hcbin(inv){
var fh;
var ic = ['low','med','low','high'];
var cbList = [ 'low', 'med', 'high','highest'];
for( var i = 0; i < ic.length; i++) {
if (ic[i] === cbList[3]) {
$scope.hdc = ic[i];
fh = true;
}
}
if (!fh){
for( var ii = 0; ii < ic.length; ii++) {
if (ic[ii] === cbList[2]) {
$scope.hdc = ic[ii];
fh = true;
}
}
}
if (!fh){
for( var iii = 0; iii < ic.length; iii++) {
if (ic[iii] === cbList[1]) {
$scope.hdc = ic[iii];
fh = true;
}
}
}
if (!fh){
for( var iiii = 0; iiii < ic.length; iiii++) {
if (ic[iiii] === cbList[0]) {
$scope.hdc = ic[iiii];
fh = true;
}
}
}
};
Try this snippet:
var ic = ['low','med','low', 'high'];
var cbList = [ 'low', 'med', 'high','highest'];
var result = null;
for (var i = (cbList.length - 1); i >=0; i--) {
if (ic.indexOf(cbList[i]) > -1) {
result = cbList[i];
break;
}
}
console.log(result);
Make sure cbList keeps the priority order(from low to highest importance) because the for is based upon that.
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.