Why is this returning an empty string? - javascript

I would like this to return s1 and s1 combined together, only the unique characters sorted in a new string called sortedString. Instead I get an empty string output.
ex input and output:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
function longest(s1, s2) {
var sortedString = '';
var a = s1.split();
var b = s2.split();
for (i=0; i < a.length; i++) {
if (!sortedString.includes(a[i])) {
sortedString.concat(a[i]);
}
}
for (j=0; j < b.length; j++) {
if (!sortedString.includes(b[j])) {
sortedString.concat(b[j]);
}
}
return sortedString.sort();
}

In javascript String type is immutable and concat method don't mutate input so when you type:
sortedString.concat(b[j]);
sortedString is never muted. You should make this instead :
sortedString = sortedString.concat(b[j]);

You need to pass an empty string to split if you want to separate the string into a list of characters.
However, I would strongly recommend you solve this declaratively:
const allChars = s1.split('').concat(s2.split(''));
return allChars
.filter((char) => allChars.indexOf(char) === allChars.lastIndexOf(char))
.sort()
.join('');

var a = "xyaabbbccccdefww";
var b = "xxxxyyyyabklmopq";
var mySet = new Set(a.split("").concat(b.split("")));
var result = Array.from(mySet).sort().join("");
console.log(result);

With ES6, you could use Set with spread syntax ... for splitting the string and for populating an array.
var a = "xyaabbbccccdefww",
b = "xxxxyyyyabklmopq",
result = [...new Set([...(a + b)])].sort().join("");
console.log(result);

Related

How to flip every character with the character next to it. Javascript

Need help inside the for loop to flip each character with the character before it.
function flip(str) {
//split string
//iterate through split string
//return joined string
var splitt = str.split('');
for(var i = 0; i < splitt.length; i++){
//flip every character with one before it
}
}
var output = flip('otatl');
console.log(output); // -> 'total'
function split(str) {
let splitt = str.split('');
for (let i=0; i<splitt.length-1; i+=2) {
const temp = splitt[i];
splitt[i] = splitt[i+1];
splitt[i+1] = temp;
}
return splitt.join('');
}
You can use ES6 destructuring assignment.
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=0; i < splitt.length; i++){
//flip every character with one before it
if (i%2 == 1) {
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
You can combine this technique with gillyb's loop pattern to reduce the iterations as follows:
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=1; i < splitt.length; i+=2){
//flip every character with one before it
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
Can do something similar with regex and array manipulation
const flip = (stringToFlip) => stringToFlip
.split(/(.{2})/) // array of strings of 2 chars
.map((e) => e.split('') // convert each string piece to array
.reverse() // reverse array
.join('') // convert array piece back to string
)
.join(''); // combine all parts
const result = flip('otatl');
console.log("flip('otatl')");
console.log(result);
If we're not restricted to for loops, this is my (slightly too code golf-ish?) answer:
const flip = (str) =>
str
.split('')
.reduce((a, v, i) => (a[i + ((i % 2) * -2 + 1)] = v, a), [])
.join('');
console.log(flip('otatl'));
console.log(flip('lfpi'));
I'm sorry I am late to the party but you can use reduce().
let input = "vanjskojfdghpja";
let output = input
.split('')
.reduce(([o,p],c,i) => i%2?[o+c+p,'']:[o,c],['',''])
.join('');
console.log(output);
.as-console-wrapper { top: 0; max-height: 100% !important; }

javascript - retrieve string right after a specific string and before the next colon

I'm a beginner in learning javascript, need to retrieve a specific part of value from the string.
below is the format of string provided by my teammates, they are a set of parameter and its value separated by a colon.
how can I retrieve the value, once input the parameter name, then return the value just before the next colon?
string = "productCat:Wine:country:Australia:year:2000:type:white wine:"
example:
if input 'productCat', then return 'Wine'
if input 'country', then return 'Australia'
if input 'year', then return '2000'
if input 'type', then return 'white wine'
thanks!
Here's an example that will be compatible with older browsers.
var string = "productCat:Wine:country:Australia:year:2000:type:white wine:"
function getPart(string, input) {
var parts = string.split(":");
for (var i = 0; i < parts.length; i = i + 2) {
if (parts[i] == input) {
return parts[i+1];
}
}
}
console.log(getPart(string, "productCat"));
First split your string into array of strings using split() function
string="productCat:Wine:country:Australia:year:2000:type:white wine:"
var array=string.split(":");
Second according to input return the value which is index+
return var x=array[array.indexOf(input)+1];
Here is a small example. Just split the string, then look for the next index if something is found.
But this is not very smart.
const string = 'productCat:Wine:country:Australia:year:2000:type:white wine';
const findNext = (data, str) => {
const array = data.split(':');
const i = array.indexOf(str);
if(i >= 0) return array[i+1];
}
console.log(findNext(string, 'productCat'));
console.log(findNext(string, 'country'));
Here is what I would do if I were you:
const string = 'productCat:Wine:country:Australia:year:2000:type:white wine';
const parseString = str => {
const array = str.split(':');
const result = {};
for(let i = 0; i<array.length; i=i+2) {
result[array[i]] = array[i+1];
}
return result;
}
const result = parseString(string);
console.log(result);
console.log(result.country);
console.log(result.year);
Just parse the string and build an object you'll use easily later ;)

Merge strings in javascript

I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?
For example:
var a = "abc"
var b = "def"
result = "adbecf"
I would use Array.from to generate an array from the strings (unicode conscious).
After that, just add a letter from each string until there's no letters left in each. Please note this solution will combine strings of uneven length (aa+bbbb=ababbb)
var a = "abc"
var b = "def"
var d = "foo 𝌆 bar mañana mañana"
function combineStrings(a,b){
var c = "";
a = Array.from(a);
b = Array.from(b);
while(a.length > 0 || b.length > 0){
if(a.length > 0)
c += a.splice(0,1);
if(b.length > 0)
c += b.splice(0,1);
}
return c;
}
var test = combineStrings(a,b);
console.log(test);
var test2 = combineStrings(a,d);
console.log(test2);
The best way to do this is to perform the following algorithm:
Iterate through string 1
For each character, if there is a character in the same position in string 2, replace the original character with both
This can be achieved with the following code:
function merge(s, t) {
return s.split("")
.map(function(v,i) {
return t[i] ? v + t[i] : v
})
.join("")
}
or the more Codegolf type answer:
s=>t=>[...s].map((v,i)=>t[i]?v+t[i]:v).join``
The simple way would be define the longest string and assigned to for loop. Also you have to add if statments for strings of uneven length, because you want to ignore undefined values of shorter string.
function mergeStrings(s1, s2){
var n = s1.length;
if(s1.length < s2.length){
n = s2.length;
}
var string = '';
for(var i = 0; i < n; i++){
if(s1[i]){
string += s1[i];
}
if(s2[i]){
string += s2[i];
}
}
return string;
}
console.log(mergeStrings('ab','lmnap'));
console.log(mergeStrings('abc','def'));
If your strings are the same length, this will work. If not you'll have to append the rest of the longer string after the loop. You can declare i outside of the loop and then use substr() to get the end of the longer string.
const a = "abc"
const b = "def"
var res = "";
for (var i = 0;i < Math.min(a.length, b.length); i++) {
res += a.charAt(i) + b.charAt(i)
}
console.log(res)
Regex or array processing and joining do the job:
let a = 'abc';
let b = 'def';
console.log(a.replace(/./g, (c, i) => c + b[i])); // 'adbecf'
console.log(Array.from(a, (c, i) => c + b[i]).join('')); // 'adbecf'
You can solve this using array spread and reduce. Split each string into an array and merge into one array and then use reduce to generate the merged string.
function mergeStrings(a, b) {
const mergedValues = [
...a.split(''),
...b.split('')
].reduce((values, currentValue) => {
if (!values.includes(currentValue)) {
values.push(currentValue);
}
return values;
}, []);
return Array.from(mergedValues).join('');
}

I want to convert the below array

I want to convert the below array:
["A:100","B:234","C:124","D:634","E:543","F:657"];
Into:
["100:234:124:634:543:657"];
How to do this?
So not sure why you would want that particular output since it would just be a single item in an array but this should work:
var testArray = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var resultArray = [];
for(var i = 0; i < testArray.length; ++i) {
resultArray.push(testArray[i].split(':')[1]);
}
var strValue = resultArray.join(':');
console.log(strValue);
resultArray = [strValue];
console.log(resultArray);
You could iterate the array, return the number on the right and join it with ':'.
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(function (a) {
return a.match(/\d*$/);
}).join(':')];
console.log(result);
Or a bit shorter
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(RegExp.prototype.exec.bind(/\d*$/)).join(':')];
console.log(result);
<script>
var arr=["A:100","B:234","C:124","D:634","E:543","F:657"];
var str='';
for(var i=0;i<arr.length;i++){
str+=arr[i].split(":")[1]+":";
}
console.log(str.substring(0, str.length - 1));
</script>
You could just keep the number behind ":" and join new elements with ":"
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var results = [data.map(x => x.split(":")[1]).join(":")];
console.log(results);
You join it with what you want :, split it by what you don't won't /\D\:/ (non digit followed by :), and then join it using an empty string '':
var arr = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var result = [arr.join(':').split(/\D\:/).join('')];
console.log(result);

find the difference use javascript

this is a leetcode question.
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
https://leetcode.com/problems/find-the-difference/
I'm trying to think a hash table way but seems I m wrong.
var findTheDifference = function(s, t) {
var hashTable = {};
var array = s.split('');
array.forEach(function (element) {
hashTable[element] = element;
});
for( var i = 0; i < t.length; i++) {
if(!hashTable.hasOwnProperty(t.charAt(i))) {
return t.charAt(i);
}
}
};
this wrong code can pass the sample Input:
Input:
s = "abcd"
t = "abcde"
Output:
e
but for large strings will be wrong
Input :"ymbgaraibkfmvocpizdydugvalagaivdbfsfbepeyccqfepzvtpyxtbadkhmwmoswrcxnargtlswqemafandgkmydtimuzvjwxvlfwlhvkrgcsithaqlcvrihrwqkpjdhgfgreqoxzfvhjzojhghfwbvpfzectwwhexthbsndovxejsntmjihchaotbgcysfdaojkjldprwyrnischrgmtvjcorypvopfmegizfkvudubnejzfqffvgdoxohuinkyygbdzmshvyqyhsozwvlhevfepdvafgkqpkmcsikfyxczcovrmwqxxbnhfzcjjcpgzjjfateajnnvlbwhyppdleahgaypxidkpwmfqwqyofwdqgxhjaxvyrzupfwesmxbjszolgwqvfiozofncbohduqgiswuiyddmwlwubetyaummenkdfptjczxemryuotrrymrfdxtrebpbjtpnuhsbnovhectpjhfhahbqrfbyxggobsweefcwxpqsspyssrmdhuelkkvyjxswjwofngpwfxvknkjviiavorwyfzlnktmfwxkvwkrwdcxjfzikdyswsuxegmhtnxjraqrdchaauazfhtklxsksbhwgjphgbasfnlwqwukprgvihntsyymdrfovaszjywuqygpvjtvlsvvqbvzsmgweiayhlubnbsitvfxawhfmfiatxvqrcwjshvovxknnxnyyfexqycrlyksderlqarqhkxyaqwlwoqcribumrqjtelhwdvaiysgjlvksrfvjlcaiwrirtkkxbwgicyhvakxgdjwnwmubkiazdjkfmotglclqndqjxethoutvjchjbkoasnnfbgrnycucfpeovruguzumgmgddqwjgdvaujhyqsqtoexmnfuluaqbxoofvotvfoiexbnprrxptchmlctzgqtkivsilwgwgvpidpvasurraqfkcmxhdapjrlrnkbklwkrvoaziznlpor"
"qhxepbshlrhoecdaodgpousbzfcqjxulatciapuftffahhlmxbufgjuxstfjvljybfxnenlacmjqoymvamphpxnolwijwcecgwbcjhgdybfffwoygikvoecdggplfohemfypxfsvdrseyhmvkoovxhdvoavsqqbrsqrkqhbtmgwaurgisloqjixfwfvwtszcxwktkwesaxsmhsvlitegrlzkvfqoiiwxbzskzoewbkxtphapavbyvhzvgrrfriddnsrftfowhdanvhjvurhljmpxvpddxmzfgwwpkjrfgqptrmumoemhfpojnxzwlrxkcafvbhlwrapubhveattfifsmiounhqusvhywnxhwrgamgnesxmzliyzisqrwvkiyderyotxhwspqrrkeczjysfujvovsfcfouykcqyjoobfdgnlswfzjmyucaxuaslzwfnetekymrwbvponiaojdqnbmboldvvitamntwnyaeppjaohwkrisrlrgwcjqqgxeqerjrbapfzurcwxhcwzugcgnirkkrxdthtbmdqgvqxilllrsbwjhwqszrjtzyetwubdrlyakzxcveufvhqugyawvkivwonvmrgnchkzdysngqdibhkyboyftxcvvjoggecjsajbuqkjjxfvynrjsnvtfvgpgveycxidhhfauvjovmnbqgoxsafknluyimkczykwdgvqwlvvgdmufxdypwnajkncoynqticfetcdafvtqszuwfmrdggifokwmkgzuxnhncmnsstffqpqbplypapctctfhqpihavligbrutxmmygiyaklqtakdidvnvrjfteazeqmbgklrgrorudayokxptswwkcircwuhcavhdparjfkjypkyxhbgwxbkvpvrtzjaetahmxevmkhdfyidhrdeejapfbafwmdqjqszwnwzgclitdhlnkaiyldwkwwzvhyorgbysyjbxsspnjdewjxbhpsvj"
Thanks for any suggestion~~~~
One approach would be to sort the strings, then find where the first difference between them is:
var str = "1122334477422";
var str2 = "15122332247744";
var sorted = str.split('').sort();
var sorted2 = str2.split('').sort()
for(var i = 0; i< sorted2.length; i++){
if(i == sorted2.length || sorted[i] != sorted2[i]){
alert(sorted2[i]);
break;
}
}
You could use a hash table for counting. Add for every letter in the original string one and subtract one for every letter in the manipulated string. Then take only the hashes with nonempty count.
var data1 = "ymbgaraibkfmvocpizdydugvalagaivdbfsfbepeyccqfepzvtpyxtbadkhmwmoswrcxnargtlswqemafandgkmydtimuzvjwxvlfwlhvkrgcsithaqlcvrihrwqkpjdhgfgreqoxzfvhjzojhghfwbvpfzectwwhexthbsndovxejsntmjihchaotbgcysfdaojkjldprwyrnischrgmtvjcorypvopfmegizfkvudubnejzfqffvgdoxohuinkyygbdzmshvyqyhsozwvlhevfepdvafgkqpkmcsikfyxczcovrmwqxxbnhfzcjjcpgzjjfateajnnvlbwhyppdleahgaypxidkpwmfqwqyofwdqgxhjaxvyrzupfwesmxbjszolgwqvfiozofncbohduqgiswuiyddmwlwubetyaummenkdfptjczxemryuotrrymrfdxtrebpbjtpnuhsbnovhectpjhfhahbqrfbyxggobsweefcwxpqsspyssrmdhuelkkvyjxswjwofngpwfxvknkjviiavorwyfzlnktmfwxkvwkrwdcxjfzikdyswsuxegmhtnxjraqrdchaauazfhtklxsksbhwgjphgbasfnlwqwukprgvihntsyymdrfovaszjywuqygpvjtvlsvvqbvzsmgweiayhlubnbsitvfxawhfmfiatxvqrcwjshvovxknnxnyyfexqycrlyksderlqarqhkxyaqwlwoqcribumrqjtelhwdvaiysgjlvksrfvjlcaiwrirtkkxbwgicyhvakxgdjwnwmubkiazdjkfmotglclqndqjxethoutvjchjbkoasnnfbgrnycucfpeovruguzumgmgddqwjgdvaujhyqsqtoexmnfuluaqbxoofvotvfoiexbnprrxptchmlctzgqtkivsilwgwgvpidpvasurraqfkcmxhdapjrlrnkbklwkrvoaziznlpor",
data2 = "qhxepbshlrhoecdaodgpousbzfcqjxulatciapuftffahhlmxbufgjuxstfjvljybfxnenlacmjqoymvamphpxnolwijwcecgwbcjhgdybfffwoygikvoecdggplfohemfypxfsvdrseyhmvkoovxhdvoavsqqbrsqrkqhbtmgwaurgisloqjixfwfvwtszcxwktkwesaxsmhsvlitegrlzkvfqoiiwxbzskzoewbkxtphapavbyvhzvgrrfriddnsrftfowhdanvhjvurhljmpxvpddxmzfgwwpkjrfgqptrmumoemhfpojnxzwlrxkcafvbhlwrapubhveattfifsmiounhqusvhywnxhwrgamgnesxmzliyzisqrwvkiyderyotxhwspqrrkeczjysfujvovsfcfouykcqyjoobfdgnlswfzjmyucaxuaslzwfnetekymrwbvponiaojdqnbmboldvvitamntwnyaeppjaohwkrisrlrgwcjqqgxeqerjrbapfzurcwxhcwzugcgnirkkrxdthtbmdqgvqxilllrsbwjhwqszrjtzyetwubdrlyakzxcveufvhqugyawvkivwonvmrgnchkzdysngqdibhkyboyftxcvvjoggecjsajbuqkjjxfvynrjsnvtfvgpgveycxidhhfauvjovmnbqgoxsafknluyimkczykwdgvqwlvvgdmufxdypwnajkncoynqticfetcdafvtqszuwfmrdggifokwmkgzuxnhncmnsstffqpqbplypapctctfhqpihavligbrutxmmygiyaklqtakdidvnvrjfteazeqmbgklrgrorudayokxptswwkcircwuhcavhdparjfkjypkyxhbgwxbkvpvrtzjaetahmxevmkhdfyidhrdeejapfbafwmdqjqszwnwzgclitdhlnkaiyldwkwwzvhyorgbysyjbxsspnjdewjxbhpsvj",
hash = Object.create(null),
count = function (a) { hash[a] = (hash[a] || 0) + this; },
result;
data1.split('').forEach(count, 1);
data2.split('').forEach(count, -1);
result = Object.keys(hash).filter(function (k) { return hash[k]; });
console.log(result);

Categories