I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(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 = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method
Related
I was trying to find out a way where I can push the first character to the last and return the rest of the string.
suppose like reverse("aeiou") should be able to return
eioua
iouae
ouaei
uaeio
function strR(str){
var a = str.split('');
var tmp =[];
a.map (item => {tmp.unshift(item)
console.log(tmp);
})
}
strR("aeiou")
aeiou
I tried a lot seems not working . If anyone can help me would be really appreciated.
let bla = "aeiou";
for (let i = 0; i < bla.length; i++) {
bla = bla.slice(1) + bla[0];
console.log(bla);
}
Try this! Alert data can print out wherever
function myFunction() {
var str = "aeiou";
var count = str.length;
for (i = 0; i < str.length; i++) {
var res = str.substring(0, 1);
var result = str.slice(1);
var data = result + res;
str = data;
alert(data);
}
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Just use substr to remove the first character and charAt to add it to the end.
var string = 'aeiou'
i=0
while (i < 10) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
Maybe you are looking for this.
let input = "aeiou";
let chunk = input.split("");
let output = [];
for(let i=0; i<chunk.length;i++){
let last = chunk.shift();
chunk.push(last);
output.push(chunk.toString().replace(/,/g, ''));
}
console.log("Output", output.toString());
Here is one liner using Array.from and slice methods.
const str = "aeiou";
const str_arr = Array.from(
new Array(str.length),
(_, i) => `${str.slice(i, str.length)}${str.slice(0, i)}`
);
console.log(str_arr);
there is a short and easier way for do that:
function FirstToEnd (str){
return str.substr(1) + str[0]
}
and for result all possible data:
function FirstToEndAllPossible(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
str = str.substr(1) + str[0];
result.push(str);
}
return result;
}
good luck :)
Try This:
var string = 'aeiou'
i=0
while (i < string.length-1) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
You can use like this. Calling Recursion - Works for all the Strings.
var InputStr = 'aeiou';
var i = 0;
var word = [];
function callqueue(InputStr, i)
{
StringLength = InputStr.length;
i = i+1;
if (i <= StringLength)
{
firstChar = InputStr.slice(0, 1);
remainStr = InputStr.substr(1);
word.push(remainStr+firstChar);
callqueue(remainStr+firstChar, i);
}
return word;
}
output = callqueue(InputStr, i);
console.log(output);
Try below code
function strR(str){
for (let i = 0; i < str.length-1; i++) {
str = str.substr(1)+str.charAt(0);
console.log(str);
}
strR('aeiou');
Your question is not quite clear. Hope the below solution works for you.
function strR(str){
var a = str.split('');
a[a.length] = a.shift();
return a.join('');
}
strR("aeiou")
/* or */
String.prototype.firstToLast = function() {
var a = this.split('');
a[a.length] = a.shift();
return a.join('');
}
"aeiou".firstToLast();
I find using an array for this kind of string manipulation a bit more readable.
In the function below, we start with splitting the string into an array.
The second step will be using the native .shit method which returns the first item in an array (in our case, the first letter) while modifying the Lastly, as we have the first character and the rest of the string we build them into a new array where we spread (...) the modified array and adding the first character at the end. The join('') method returns a string out of the new array.
function firstToLast (str) {
const split = str.split('');
const first = split.shift();
return [...split, first].join('');
}
Hopefully it's clear and helps with what you were trying to achieve
My go-to would be to use JavaScripts built-in array methods. You can break a string into an array of single characters using split with no parameters, and put it back together using join with an empty string as a parameter.
let word = 'sydney'
function rotate (anyword) {
let wordarray= anyword.split()
let chartomove = wordarray.splice(0, 1)[0]
wordarray.push(chartomove)
return wordarray.join('')
}
rotate(word) // returns 'ydneys'
I am trying to find common strings in given two strings.
Example:
string1 = "mega,cloud,two,website,final"
string2 = "window,penguin,literature,network,fun,cloud,final,sausage"
answer = "cloud,final,two"
So far this is what i got:
function commonWords(first, second) {
var words = first.match(/\w+/g);
var result = "";
words.sort();
for(var i = 0; i < words.length; i++){
if(second.includes(words[i])){
result = result.concat(words[i]);
result += ",";
}
}
result = result.substr(0, result.length -1);
return result;
}
But the result that i got is :
answer = cloud,final
Can you help me out please? First time asking question on StackOverFlow, so sorry for the typing.
What I would do is first split on the two strings, then do a reduce and check if the other string includes the current string. If so add them to a new array.
const string1 = "mega,cloud,two,website,final"
const string2 = "window,penguin,literature,network,fun,cloud,final,sausage"
const array1 = string1.split(',')
const array2 = string2.split(',')
const result = array1.reduce((arr, val) => array2.includes(val) ? arr.concat(val) : arr, [])
console.log(result)
// Convert it to a string if desired
console.log(result.toString())
Try the following:
string1 = "mega,cloud,two,website,final"
string2 = "window,penguin,literature,network,fun,cloud,final,sausage";
var arr1= string1.split(",");
var arr2 = string2.split(",");
var result = [];
arr1.forEach(function(str){
arr2.forEach(function(str2){
if(str2.indexOf(str) != -1)
result.push(str);
});
});
var answer = result.join(",");
console.log(answer);
The problem with your function is you also converting the string to into second as an array.
function commonWords(first, second) {
var words = first.match(/\w+/g); // word is a array type
var result = "";
words.sort();
for(var i = 0; i < words.length; i++){
if(second.includes(words[i])){ //second should be string type
result = result.concat(words[i]);
result += ",";
}
}
result = result.substr(0, result.length -1);
return result;
}
Or you can try this
first = "mega,cloud,two,website,final"
second = "window,penguin,literature,network,fun,cloud,final,sausage"
function commonWords(first, second) {
var words = first.match(/\w+/g);
var result = "";
words.sort();
for(var i = 0; i < words.length; i++){
if(second.includes(words[i])){
result = result.concat(words[i]);
result += ",";
}
}
result = result.substr(0, result.length -1);
return result;
}
console.log(commonWords(first, second));
I would convert each string to an array of words with .split(','). Then filter the first array with .filter by checking if each item of the array is in the other one:
string1 = "mega,Cloud,two,website,final"
string2 = "window,penguin,literature,network,fun,cloud,final,sausage"
array1 = string1.toLowerCase().split(',')
array2 = string2.toLowerCase().split(',')
var a = array1.filter(word => -1 !== array2.indexOf(word));
console.log(a)
Before converting the string to an array I have applied .toLowerCase() so that the script can return cloud in the result if it appears in the first one as "Cloud" and in the second as "cloud"
I have a string similiar to document.cookie:
var str = 'foo=bar, baz=quux';
Converting it into an array is very easy:
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
str[i].split('=');
}
It produces something like this:
[['foo', 'bar'], ['baz', 'quux']]
Converting to an object (which would be more appropriate in this case) is harder.
str = JSON.parse('{' + str.replace('=', ':') + '}');
This produces an object like this, which is invalid:
{foo: bar, baz: quux}
I want an object like this:
{'foo': 'bar', 'baz': 'quux'}
Note: I've used single quotes in my examples, but when posting your code, if you're using JSON.parse(), keep in your mind that it requires double quotes instead of single.
Update
Thanks for everybody. Here's the function I'll use (for future reference):
function str_obj(str) {
str = str.split(', ');
var result = {};
for (var i = 0; i < str.length; i++) {
var cur = str[i].split('=');
result[cur[0]] = cur[1];
}
return result;
}
The shortest way
document.cookie.split('; ').reduce((prev, current) => {
const [name, ...value] = current.split('=');
prev[name] = value.join('=');
return prev;
}, {});
Why exactly do you need JSON.parse in here? Modifying your arrays example
let str = "foo=bar; baz=quux";
str = str.split('; ');
const result = {};
for (let i in str) {
const cur = str[i].split('=');
result[cur[0]] = cur[1];
}
console.log(result);
note : The document.cookie (question headline) is semicolon separated and not comma separated (question) ...
An alternative using reduce :
var str = 'foo=bar; baz=quux';
var obj = str.split(/[;] */).reduce(function(result, pairStr) {
var arr = pairStr.split('=');
if (arr.length === 2) { result[arr[0]] = arr[1]; }
return result;
}, {});
A way to parse cookies using native methods like URLSearchParams and Object.fromEntries, avoiding loops and temporary variables.
Parsing document.cookie:
Object.fromEntries(new URLSearchParams(document.cookie.replace(/; /g, "&")))
For the scope of the question (cookies are separated by , and stored in variable str)
Object.fromEntries(new URLSearchParams(str.replace(/, /g, "&")))
Given an array a containing your intermediate form:
[['foo', 'bar'], ['baz', 'quux']]
then simply:
var obj = {};
for (var i = 0; i < a.length; ++i) {
var tmp = a[i];
obj[tmp[0]] = tmp[1];
}
To convert it to an object, just do that from the beginning:
var obj = {};
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
var tmp = str[i].split('=');
obj[tmp[0]] = tmp[1];
}
Then, if you want JSON out of it:
var jsonString = JSON.stringify(obj);
parse cookies (IE9+):
document.cookie.split('; ').reduce((result, v) => {
const k = v.split('=');
result[k[0]] = k[1];
return result;
}, {})
I'm a fan of John Resig's "Search and don't replace" method for this sort of thing:
var str = 'foo=bar, baz=quux',
arr = [],
res = '{';
str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) {
arr.push('"' + key + '":"' + value + '"');
});
res += arr.join(",") + "}";
alert(res);
Working example: http://jsfiddle.net/cm6MT/.
Makes things a lot simpler without the need for JSON support. Of course, it's just as easy to use the same regular expression with exec() or match().
Whoops, I thought you wanted to convert to a JSON string, not an object. In that case, you only need to modify the code slightly:
var str = 'foo=bar, baz=quux',
res = {};
str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) {
res[key] = value;
});
console.log(res.foo);
//-> "bar"
Working example 2: http://jsfiddle.net/cm6MT/1/
Most of the above solutions fail with the __gads cookie that Google sets because it uses a '=' character in the cookie value.
The solution is to use a regular expression instead of calling split('='):
document.cookie.split(';').reduce((prev, current) => {
const [name, value] = current.split(/\s?(.*?)=(.*)/).splice(1, 2);
prev[name] = value;
return prev;
}, {});
That's pretty crappy data, as long as its not using ,= this would work on that data
var text = 'foo=bar, baz=quux',
pattern = new RegExp(/\b([^=,]+)=([^=,]+)\b/g),
obj = {};
while (match = pattern.exec(text)) obj[match[1]] = match[2];
console.dir(obj);
An alternate version of your updated solution that checks for the null/empty string and just returns an empty object and also allows for custom delimiters.
function stringToObject(str, delimiter) {
var result = {};
if (str && str.length > 0) {
str = str.split(delimiter || ',');
for (var i = 0; i < str.length; i++) {
var cur = str[i].split('=');
result[cur[0]] = cur[1];
}
}
return result;
}
first thing that occurred to me, I'll leave it as the original version, but cookies should not be empty otherwise there will be a json parse error
JSON.parse(`{"${document.cookie.replace(/=/g,'":"').replace(/; /g,'","')}"}`)
fast and reliable version - cookie to object
let c=document.cookie.split('; '),i=c.length,o={};
while(i--){let a=c[i].split('=');o[a[0]]=a[1]}
and short function for get single cookie
getCookie=e=>(e=document.cookie.match(e+'=([^;]+)'),e&&e[1])
function getCookie(){
var o=document.cookie.split("; ");
var r=[{}];
for(var i=0;i<o.length;i++){
r[o[i].split("=")[0]] = o[i].split("=")[1];
}
return r;
}
Just call getCookie() and it will return all cookies from the current website.
If you have a cookie called 'mycookie' you can run getCookie()['mycookie']; and it will return the value of the cookie 'mycookie'.
There is also a One-Line option:
function getCookie(){var o=document.cookie.split("; ");var r=[{}];for(var i=0;i<o.length;i++){r[o[i].split("=")[0]] = o[i].split("=")[1];}return r;}
This one can be used with the same methods as above.
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!
What I have:
var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
What I need:
["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$
Example:
difference.$.user.$.otherinformation should be parsed to contain:
difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.
Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.
How best can I take this to closure?
Current flawed implementation:
for(var i=0; i<array.length; i++){
// next, replace all array field references with $ as that is what autoform's pick() requires
// /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
array[i] = array[i].replace(/\.\d+\./g,".$.");
if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
console.log("Substring without .$. " + array[i].substring(0, array[i].indexOf('.$.')));
console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')));
}
}
// finally remove any duplicates if any
array = _.uniq(array);
A functional single liner could be;
var array = ["authentication.$.order", "difference.$.user.$.otherinformation"],
result = array.reduce((r,s) => r.concat(s.split(".").reduce((p,c,i) => p.concat(i ? p[p.length-1] + "." + c : c), [])), []);
console.log(result);
You can use this function inside your array loop.
var test = "difference.$.user.$.otherinformation";
function toArray(testString) {
var testArr = testString.split(".")
var tempString = "";
var finalArray = [];
for (var i = 0; i < testArr.length; i++) {
var toTest = testArr[i];
if (toTest == "$") {
tempString += ".$"
} else {
if (i != 0) {
tempString += ".";
}
tempString += toTest;
}
finalArray.push(tempString)
}
return finalArray;
}
console.log(toArray(test))
I used a Regex expression to grab everything until the last occurrence of .$ and the chopped it, until there was nothing left. Reverse at the end.
let results = [];
let found = true;
const regex = /^(.*)\.\$/g;
let str = `difference.\$.user.\$.otherinformation`;
let m;
results.push(str);
while(found) {
found = false;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(m.length > 0) {
found = true;
results.push(m[0]);
str = m[1];
}
}
}
results.push(str);
results = results.reverse();
// Concat this onto another array and keep concatenating for the other strings
console.log(results);
You will just need to loop this over your array, store the results in a temp array and keep concatenating them onto a final array.
https://jsfiddle.net/9pa3hr46/
You can use reduce as follows:
const dat = ["authentication.$.order", "difference.$.user.$.otherinformation"];
const ret = dat.reduce((acc, val) => {
const props = val.split('.');
let concat = '';
return acc.concat(props.reduce((acc1, prop) => {
concat+= (concat ? '.'+ prop : prop);
acc1.push(concat);
return acc1;
}, []));
}, [])
console.log(ret);
Actually recursion is unnecessary for this problem. You can use regular loop with subloop instead.
All you need is:
split each occurence in the array into substrings;
build a series of accumulated values from these substrings;
replace the current element of the array with this series.
Moreover, in order to make replacement to work properly you have to iterate the array in reverse order. BTW in this case you don't need to remove duplicates in the array.
So the code should look like this:
var array = ["authentication.$.order", "difference.$.user.$.otherinformation"];
var SEP = '.$.';
for (var i = array.length-1; i >= 0; i--){
var v = array[i];
var subs = v.replace(/\.\d+\./g, SEP).split(SEP)
if (subs.length <= 1) continue;
var acc = subs[0], elems = [acc];
for (var n = subs.length-1, j = 0; j < n; j++) {
elems[j * 2 + 1] = (acc += SEP);
elems[j * 2 + 2] = (acc += subs[j]);
}
array.splice.apply(array, [i, 1].concat(elems));
}
console.log(array);
Use a simple for loop like below:
var str = "difference.$.user.$.otherinformation";
var sub, initial = "";
var start = 0;
var pos = str.indexOf('.');
for (; pos != -1; pos = str.indexOf('.', pos + 1)) {
sub = str.substring(start, pos);
console.log(initial + sub);
initial += sub;
start = pos;
}
console.log(str);
If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);