In the string below, I want to split the string separated by "|" (which i can do)and would then like to compare the first part and the boolean part of each such string with the same parts of another string.
var str = "Jacobs21]2]0]Ronan]false|Tom]2]0]Joseph]true|Jacobs21]2]0]NAME$$ALL]false|";
In the string above, Jacobs21]2]0]Ronan]false is one string and so on.
I am more interested in the Jacobs21 part of this string and the boolean value appearing at its end which is "false" here.
Now, I want to compare the first and the last part joined as a single string to form Jocobs21false and similarly, for the another string tomtrue and make a comparison and see if there are any similar matches?
var detailsArray = str.split("|");
var res = [];
for (var i = 0; i < detailsArray.length - 1; i++) {
finalArray = detailsArray[i].toString().split("]");
var name = finalArray[0];
var booleanString = finalArray[4];
res[i] = name.concat(booleanString);
}
for (var j = 0; j < res.length - 1; j++) {
if (res[i] == res[i + 1]) {
//do your stuff
}
}
Related
Write a function that accepts a string where letters are grouped together and returns new string with each letter followed by a count of the number of times it appears.
example : ('aeebbccd') should produce // 'a1e2b2c2d1'
function strExpand(str) {
let results = ""
for (let i = 0; i < str.length; i++) {
let charAt = str.charAt(i)
let count = 0
results += charAt
for (let j = 0; j < str.length; j++) {
if (str.charAt(j) === charAt) {
count++;
}
}
results += count;
}
return results;
}
with the input 'aeebbccd' I am getting 'a1e2e2b2b2c2c2d1' instead of 'a1e2b2c2d1'
This function is adding a number after each character, which is the number of times this character appears anywhere in the string. You could instead do it like this to get the result you want.
function strExpand(str) {
let output = "";
// Iterate through each character of the string, appending
// to the output string each time
for (let i = 0; i < str.length; i++) {
let count = 1;
// If the next character is the same, increase the count
// and increment the index in the string
while (str[i + 1] == str[i]) {
count++;
i++;
}
// Add the character and the count to the output string
output += str[i] + count;
}
return output;
}
For sake of completeness,
how about a Regex?
const pattern = /(.)\1*/g; // put a char that exists in a capture group, then see if it repeats directly after
const s = 'aeebbccd';
var result = '';
for (match of s.match(pattern)) {
let this_group = match;
let this_len = match.length;
result = result + this_group[0] + this_len; // get only the first letter from the group
}
console.log(result); // a1e2b2c2d1
This would to the job. edit: hah i see im late :D, but still nice functional way to solve that.
/**
* #param string to count
* #return string $characterA$count. ex. abbccc -> a1b2c3
*/
function toCharacterCountString(str) {
return Array.from(new Set(str).values())
.map(char => {
return `${char}${(str.match(new RegExp(char, "g")) || []).length}`;
}).join('');
}
console.log(toCharacterCountString('abbccc')); // a1b2c3
console.log(toCharacterCountString('aeebbccd')); // a1e2b2c2d1
Write a function called strLetterCount which accepts a string and returns a new string with each character followed by the number of times it appears in the string. The characters should be returned in the same order as the string with each unique letter followed by the number of times it appears in the string.
My code so far is:
//write function format with argument
function strLetterCount (str){
//initialize var to hold results for charAt
let charAt = '';
let count = 0;
for(let i = 0; i < str.length; i++){
str.charAt(i);
results = str.charAt(i);
for (let j = 0; j < str.length ; j++){
if(str[i] === str){
count++
results = str.charAt(i) + count++
}
}
return results;
}
}
strLetterCount('taco'); //'t1a1c1o1'
//function should pass a string as argument
//loop through the string and if a new char is entered store that
//loop through string again and count num of new char
//returns a new string push charAt and numOfOcc
It should return the output of 't1a1c101' , however, I am only getting it to loop through the string once and return the first value of 't' but it's not counting the occurrences? I cant identify where to change my logic to hold the count of occurence?
I guess you try to achieve something like this.
Each letter will appear in output string with the same number of occurence as in the input string. I'm not sure that's what you want, but that's the thing the strLetterCount function intends to do.
function strLetterCount (str){
let results = ""
//initialize var to hold results for charAt
for(let i = 0; i < str.length; i++)
{
// Get current char and store it into the results
// We will add the count in a second loop
let charAt = str.charAt(i)
let count = 0
results += charAt
for (let j = 0; j < str.length ; j++)
{
if(str.charAt(j) === charAt)
{
count++
}
}
results += count
}
return results;
}
Assuming that you don't need a count of each letter to be in the same position it started in, i.e. "started" can equal "s1t2a1r1e1d1" instead of "s1t2a1r1t2e1d1", than this should do the trick.
function strLetterCount (str){
// create an object to store each letter
const countObj = {}
// iterate over the string
for (let i = 0; i < str.length; i++) {
// if the letter isn't stored in the object, add it with a count of one
if (!countObj[str[i]]) {
countObj[str[i]] = 1;
} else {
// if the letter is already in the object, increment the count
countObj[str[i]]++;
}
}
// create a string to add the letter / count to
let outStr = "";
// iterate over the object to create the string
for (const letter in countObj) {
outStr += `${letter}${countObj[letter]}`;
}
// return the string
return outStr;
}
This would satisfy the requirements
function strLetterCount(str) {
// split the string to array
let strArr = str.split("");
// new array without duplicate letter
let strArrWithoutDuplicates = strArr.filter((value, idx, arr) => arr.indexOf(value) === idx);
let retString = "";
// loop through the "strArrWithoutDuplicates" array to find the number of times
// each elemet appears on the original array
strArrWithoutDuplicates.forEach(letter => {
retString += letter;
retString += strArr.filter((value) => (value === letter)).length;
});
return retString;
}
let a = strLetterCount('taco'); //'t1a1c1o1'
console.log(a)
I want to loop through set of strings and break them into sub strings by removing two characters and storing them into an array.
lets say two stings are returned, the number of characters will always be multiple of 2.
AADDFFCC
GGDD
The first string will give me AADDFF,AADD,AA
The second string will give me GG.
i want to store all sub string into a single array.
So based upon above example i should end up with.
subString = ["AADDFF","AADD","AA","GG"]
This is my incomplete attempt.
var StringArray = ["AADDFFCC","GGDD"] //this could be indefinite length
var subString = [];
var StringArrayLength = StringArray.length;
var loopCurrentString;
var loopCurrentSubString
for (var i = 0; i < StringArrayLength; i += 2) {
loopCurrentString = StringArray[i];
loopCurrentSubString = loopCurrentString.substring(0, loopCurrentString.length - 2);
}
for (var i = 0; i < StringArrayLength; i ++) {
//get element
loopCurrentString = StringArray[i];
//add substrings in the array
while(loopCurrentString.length>2){
loopCurrentSubString = loopCurrentString.substring(0, loopCurrentString.length - 2);
substring.push(loopCurrentSubString);
}
}
Here is an implementation with nested for loops:
const data = ["AADDFFCC", "GGDD"]
const endResult = []
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j += 2) {
if (j != 0)
endResult.push(data[i].slice(0, data[i].length - j))
}
}
console.log(endResult)
You could do this by using reduceRight to chunk the array into the desired pieces starting from the right side:
const data = ["AADDFFCC","GGDD"]
const chunkBy = (arr, by=2) => [...arr].reduceRight((r,c,i,a) =>
((((a.length-1) - i)%by == 0 && a.length-1 != i) ?
r.push(a.slice(0, i+1).reduce((r,c) => `${r}${c}`)) :
0, r),[])
console.log(data.reduce((r,c) => [...chunkBy(r), ...chunkBy(c)]))
And on the end stitch them together via ES6 spread operator.
I'm trying to double my string xyz to xxyyzz in JS but can't get it to return correctly. What am I doing wrong?
<script>
string=["xyz"];
for (var i=0;i<string.length;i++)
{
document.write(string[i]*2);
}
</script>
var string = "xyz".split('').map(function(s){return s+s}).join('');
I like doing it using array maps instead of for loops. It seems cleaner to me.
The correct way would be to add the strings together (concatenation) instead of using a multiply by 2 which won't work. See below:
<script type="text/javascript">
var string = ['xyz'];
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}
</script>
A few problems:
You've declared string inside an array, giving string.length a value of 1 as that's the number of elements
You can't multiply strings, unfortunately. You need to concatenate them
Here's how I'd do it:
var string = "xyz";
var newString = "";
for (var i = 0; i < string.length; i++)
newString += string[i] + string[i];
document.write(newString);
You didn't declared a string, you declared an array of string with 1-length.
Your are multiplying position of array (string[i]*2), trying concatenating (string[i] + string[i]).
This should work:
var string = 'xyz';
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}
I have been stumped on this problem for a few hours now and am making no progress. I feel like this should be simple. I am trying to Remove duplicate characters in a String without using methods such as Filter or a Reg ex.
Here is my current code:
var duplicate = function(string) {
var newString = string.split("");
var finalArrayWithNoDuplicates = []
for (var i = 0; i < newString.length; i++){
for (var=0; j < newString.length; i++){
while(newString[i])
if (newString[i] !== newString[j]){
}
}
}
return finalArrayWithNoDuplicates.join("");
};
I am able to filter one letter at a time but as I progress down the chain in the while statement I am adding letters that were filtered out originally.
All of the algorithm tutorials for this algorithm are in Java that I have been finding. Is there a way to do this with only using a a for and while loops?
There are several things wrong with the proposed code:
It has serious errors (the inner loop is written all wrong)
You don't need to involve arrays at all, strings will do just fine
The "if char !== other char" check will never provide enough information to act on
Here's an alternative version using for loops and the same basic idea:
function deduplicate(str) {
var result = "";
for (var i = 0; i < str.length; ++i) {
var found = false;
for (var j = 0; j < i; ++j) {
if (str[i] == str[j]) {
found = true;
break;
}
}
if (!found) result += str[i];
}
return result;
}
Each character str[i] in the input string is compared to all characters str[j] that precede it (there is no point in comparing to characters that follow it because we are going to process those when their turn comes up anyway). If the character is not equal to any of those that precede it then we know it's the first of its kind to appear and include it in the result.
Note that this algorithm has O(n²) performance, which is very poor compared to other possible approaches. Its main selling point is that it is straightforward and that everything happens "in front of your eyes".
Here is a slightly modified version of your function that uses an object to keep track of which letters have already been encountered:
var duplicate = function(string) {
var finalArrayWithNoDuplicates = [];
var seen = {};
for (var i = 0; i < string.length; i++) {
if (!seen[string[i]]) {
finalArrayWithNoDuplicates.push(string[i]);
seen[string[i]] = 1;
}
}
return finalArrayWithNoDuplicates.join("");
};
No need for two nested for-loops
No need for "while" loop as well
in the following line of code there are two errors: for (var=0; j < newString.length; i++){ first one is var=0 (compilation error) and second is theat you increment i instead of j
It can be done by adding only unique elements (that don't appear twice) to finalArrayWithNoDuplicates
as follows:
var duplicate = function(newString) {
var finalArrayWithNoDuplicates = []
var x = 0;
for (var i = 0; i < newString.length; i++){
// if the char appears in another index
// or if it's already in the result - don't add it
if (newString.lastIndexOf(newString[i]) !== i || finalArrayWithNoDuplicates.indexOf(newString[i]) > -1){
continue;
}
else{
finalArrayWithNoDuplicates[x++] = newString[i];
}
}
return finalArrayWithNoDuplicates.join("");
};
var arr = [1,2,3,4,5,4,5,6,7];
alert(duplicate(arr));
OUTPUT:
1234567