SHEKHAR SHETE SHEKHAR SHETE - 3 months ago 11
Javascript Question

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

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#
?

Answer

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: