How to set sequence for exact consecutive elements of csv string? - javascript

I have a string csv containing PORTCODE and latitude longitude of location. I use these values to plot the marker on google map.
Eg csv string:
ANC|61.2181:149.9003,
ANC|61.2181:149.9003,
TLK|62.3209:150.1066,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
DNL|63.1148:151.1926,
TLK|62.3209:150.1066,
TLK|62.3209:150.1066,
ALE|60.9543:149.1599
i want to autonumber SIMILAR PORTCODE sequence separated with pipe symbol '|' for the PORTCODE which are EXACT Consecutive next element.
Required out put:
ANC|61.2181:149.9003:1|2,
TLK|62.3209:150.1066:3,
DNL|63.1148:151.1926:4|5|6,
TLK|62.3209:150.1066:7|8,
ALE|60.9543:149.1599:9
Any solution using jquery/javascript/c# ?

There's probably a neater/shorter way to do this, but here's the first second way that came to mind using JavaScript:
var input = "ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599";
var output = input.split(",\n").reduce(function(p,c,i,a) {
if (i === 1) p += ":1";
return p + (c === a[i-1] ? "|" : ",\n" + c + ":") + (i+1);
});
console.log(output);
I've assumed each line ends with a single \n character, but obviously you can adjust for \r or whatever.
Further reading:
the string .split() method
the array .reduce() method

You can make something like that.
var csv = 'ANC|61.2181:149.9003,\nANC|61.2181:149.9003,\nTLK|62.3209:150.1066,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nDNL|63.1148:151.1926,\nTLK|62.3209:150.1066,\nTLK|62.3209:150.1066,\nALE|60.9543:149.1599'.split(',\n');
//count entry :
var results = [];
var j = -1;
var previous = "";
for (i = 0; i < csv.length; i++) {
if (previous === csv[i]) {
results [j] += '|' + (i+1);
} else {
j += 1;
previous = csv[i];
results [j] = csv[i] + ':' + (i+1);
}
}
//And reforme your csv
console.log(results.join(',\n'));
Further reading:
the string .split() method
the array .join() method

here is C# way to do,
public string[] data = { "ANC|61.2181:149.9003", "ANC|61.2181:149.9003", "TLK|62.3209:150.1066", "DNL|63.1148:151.1926", "DNL|63.1148:151.1926", "TLK|62.3209:150.1066", "TLK|62.3209:150.1066", "ALE|60.9543:149.1599", "DNL|63.1148:151.1926" };
int counter = 0;
var output = data.Select(x => new Tuple<string, int>(x, counter++))
.GroupBy(x => x.Item1)
.Select(h => h.Key + ":"+ string.Join("|", h.Select(x => x.Item2)));
output would be ANC|61.2181:149.9003:0|1,TLK|62.3209:150.1066:2|5|6,DNL|63.1148:151.1926:3|4|8,ALE|60.9543:149.1599:7

Related

how to wrap two string with double quote that are separated by comma in JS

I am very new to coding. I am having issue solving this following:
taking a data block ex:
1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42
and covert into something like
1963,"john, doe","Williwanka,tp",jane,4200,1300,19.63,-42
I know I can use split() and join() however having trouble sorting through the string separated by comma "," and add double quote.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var myArray = text.split(";");
var newText = "";
for (var i = 0; i <= myArray.length; i++) {
if (myArray.indexOf(i) == ",") {
let newText = '"' + fruits.join('","') + '"';
} else {
newText += text.index(i);
}
}
return newText
Split by semicolons, then for each part, check if it includes a comma. If it does, wrap it in quotes, otherwise, don't change it. Then join the result into a string.
const text = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42";
const parts = text.split(";");
const result = parts.map((p) => p.includes(",") ? `"${p}"` : p).join(",");
console.log(result);
You could use the regex /([^;]+)(?:;|$)/ and replace the first capturing group with " if it cannot be parsed to a number.
const input = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42",
replacer = (_, p1) => isNaN(p1) ? `"${p1}",` : `${p1},`,
output = input.replace(/([^;]+)(?:;|$)/g, replacer).slice(0, -1);
console.log(output)
While the previous answers are correctly fine, it might be hard to understand how they work for a novice programmer.
Allow me to fix give you another answer below which is based on a simple loop like the OPs original code.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var partsArray = text.split(";");
var newText = "";
for (var i = 0; i < partsArray.length; i++) {
let onePart = partsArray[i];
if (onePart.includes(",")) {
newText += `"${onePart}"`;
} else {
newText += onePart;
}
newText += ",";
}
console.log(newText);

How can I stringify output from a for loop?

I have the following for loop and I would like the output of the loop to be stringified into a query string as shown in the desired output below. I'm using the qs npm package for stringifying URLs.
What's the best way of going about getting the desired output?
for (i = 0; i < 2; i++) {
var foo = "pr" + [i] + "va";
var bar = "value";
};
//Desired output: ?pr0va=value&pr1va=value
Instead of creating variables - create String and do concatenation in every loop.
Check my code snippet.
var query = "";
var size = 2;
for (i = 0; i < size; i++) {
query += "pr" + [i] + "va=value";
if (i+1<size)
query += "&";
};
console.log(query);
This should work for you.
function test () {
var i =0;
var arr = [];
for(i=0;i<2;i++) {
arr.push( "pr" + [i] + "va=value" );
}
console.log('?' + arr.join('&').toString())
}
Something like this?
var output = '?';
for (i = 0; i < 2; i++) {
var foo = "pr" + [i] + "va";
var bar = "value";
output += foo + "=" + bar + "&";
};
console.log(output);
//Desired output: ?pr0va=value&pr1va=value
You can do it like this.
var output = "?";
for (i = 0; i < 2; i++) {
output += "pr" + [i] + "va=value&";
};
console.log(output.slice(0, -1))
If I were to review such code I would prefer to see the following:
Avoid concatenation.
Use of functional programming.
Reasonable usage of 3rd parties - so yes for querystring
All of those are for readability, simplicity and maintainability benefits. And I admit it is arguable.. so please don't argue :)
I will use your code as a baseline and improve from there
for (i = 0; i < 2; i++) {
var foo = "pr" + [i] + "va";
var bar = "value";
};
Note that your snippet is incomplete, and so, at the beginning mine will not be complete too, but I'll get there
Avoid concatenation
I will avoid concatenation using template literal
for (i = 0; i < 2; i++) {
`pr${i}va=value`;
};
Use of functional programming
I will iterate over numbers using an array, and reduce to construct an object
const queryParams = Array(2).fill().reduce((object, value, index) => {
object[`pr${index}va`] = 'value';
return object;
} , {} )
Using 3rd parties
Now I will use querystring to turn queryParams to a query string
return querystring.stringify(queryParams);
All together now
/**
* #param {number} count - number of query parameters to generate
* #returns {string} query string. for example for count=2 will return `pr1va=value&pr2va=value`
**/
function generateQueryString(count=2){
const queryParams = Array(count).fill().reduce((object, value, index) => { // convert N number to key-value map using reduce
object[`pr${index}va`] = 'value';
return object;
} , {} );
return querystring.stringify(queryParams);
}
You can create an array of size, loop and then join it:
function createString(size) {
return new Array(size).fill(0).map((v, i) => {
return "pr" + i + "va=value";
}).join("&");
}
console.log(createString(2));

javascript replace string/html from array

I try to create a system replacement for ToolTip.
I already create a version but its not quite optimal (search a better way to do it)
here's a fiddle : http://jsfiddle.net/forX/Lwgrug24/
I create a dictionary (array[key]->value). the array is order by length of the key.
each key is a word or an expression, the value is the definition of the expression.
So, I replace the expression by a span (could/should be a div). The span is used for the tooltip (I use the data-title as tooltip text).
because some word is reused in expression, I need to remove expression already with tooltip (in real life think of father/grandfather, you dont want the definition of father inside grandfather). For replacement I use a ramdom value. That's the worst of this code.
You could make comment or post a new way to do it. maybe someone already did it.
Clarification :
I think my way to do it is wrong by using a string for replacement. Or it could be more secure. How should I do it?
html :
<div class="container">
one two three four five six seven eight nine ten
</div>
javascript :
$(function() {
var list = [
{'k':'one two three four five','v':'First five number.'},
{'k':'four five six seven','v':'middle number.'},
{'k':'six seven eight','v':'second middle number.'},
{'k':'two','v':'number two.'},
{'k':'six','v':'number six.'},
{'k':'ten','v':'number ten.'}
];
$(".container").each(function(){
var replacement = new Array();
for (i = 0; i < list.length; i++) {
var val = list[i];
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
replacement[rString + "_k"] = htmlEncode(val["k"]);
replacement[rString + "_v"] = htmlEncode(val["v"]);
var re = new RegExp("(" + val["k"] + ")","g");
$(":contains('" + val["k"] + "')",$(this).parent()).html(function(_, html) {
var newItem = '<span class="itemWithDescription" '
+ 'data-title="' + rString + "_v" + '">'
+ rString + "_k"
+ '</span>';
return html.replace(re, newItem);
});
}
for (var k in replacement){
$(this).html($(this).html().replace(k,replacement[k]));
console.log("Key is " + k + ", value is : " + replacement[k]);
}
});
$(document).tooltip({
items:'.itemWithDescription',
tooltipClass:'Tip',
content: function(){
var title = $(this).attr("data-title");
if (title == ""){
title = $(this).attr("title"); //custom tooltips
}
return title;
}
});
});
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
I added a little thing. on the random function, I put a | and } for every char, its bigger but there's not much chance to have a conflic with an expression.
for (var i = length; i > 0; --i) result += '|' + ( chars[Math.round(Math.random() * (chars.length - 1))] ) + '}' ;
http://jsfiddle.net/forX/Lwgrug24/3/

Remove comma from javascript array

Hi all I am framing a url with Query string in javascript as follows every thing works fine but a comm is coming in between the query string so can some one help me
<script type="text/javascript">
function RedirectLocation() {
var cntrl = "Q1;Q2";
var str_array = cntrl.split(';');
var cnt = str_array.length;
if (cnt == 0) {
location.href = '/callBack.aspx';
}
else {
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
if (i != str_array.length - 1) {
arr.push('&');
}
}
location.href = '/Sample.aspx?' + arr;
}
}
</script>
This is giving me the query string as follows Sample.aspx?Q1=1,&,Q2=1 I need this to be like `Sample.aspx?Q1=1&Q2=1
To remove the commas from a string you could simply do
s = s.replace(/,/g,'');
But in your specific case, what you want is not to add the commas. Change
location.href = '/Sample.aspx?' + arr;
to
location.href = '/Sample.aspx?' + arr.join('');
What happens is that adding an array to a string calls toString on that array and that function adds the commas :
""+["a","b"] gives "a,b"
Don't rely on the implicit string conversion (which concatenates the array elements with a comma as separator), explicitly .join the array elements with &:
var arr = [];
for (var i = 0; i < str_array.length; i++) {
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
arr.push(str_array[i] + '=1');
}
location.href = '/Sample.aspx?' + arr.join('&');
Think about it like this: You have a set of name=value entries which you want to have separated by &.
You can use arr.join(glue) to concatenate Array elements with something inbetween. In your case glue would be an empty string arr.join("").

remove all empty values from url

I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}

Categories