What is the best way to establish a sequence for consecutive elements in a csv string?

I've got a string csv that holds PORTCODE and latitude longitude coordinates of a location. Using these values, I plot markers on a google map.

Example 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 automatically number SIMILAR PORTCODE sequences separated by pipe symbol '|' for PORTCODEs that are EXACTLY consecutive.

Desired output:

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

Is there any solution using jquery/javascript/c#?

Answer №1

If you're looking for a more streamlined approach, here's an alternative method I came up with 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);

Note that the assumption here is that each line is terminated with a single \n character, but this can easily be adjusted for other line endings like \r.

For more information, you can check out:

Answer №2

Creating something similar to this is possible.

 var text = '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 entries :

var resultsArray = [];
var index = -1;
var previousText = "";
for (i = 0; i < text.length; i++) {
  if (previousText === text[i]) {
    resultsArray[index] += '|' + (i+1);
  } else {
    index += 1;
    previousText = text[i];
    resultsArray[index] = text[i] + ':' + (i+1);
  }
}

//Reformat the text
console.log(resultsArray.join(',\n'));

For more information:

Answer №3

Check out this C# method to achieve the same result:

string[] values = { "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 count = 0;
var result = values.Select(x => new Tuple<string, int>(x, count++))
           .GroupBy(x => x.Item1)
           .Select(h => h.Key + ":"+ string.Join("|", h.Select(x => x.Item2)));

The expected output will 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...

The validation of radio input signals results in an error being returned

For a while now, I've been trying to solve the issue with radio button validation in my current project. Surprisingly, it works fine when there are no other functions in the form besides the radio buttons themselves. I suspect that the problem lies wi ...

inject custom styles into a Material-UI styled component

Although I have come across similar questions, none seem to directly address my current situation. I am in the process of transitioning from MUI v4 to MUI v5 and have encountered various scenarios where a specific style is applied externally. For instance ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Leveraging the power of fullpage.js to activate Velocity.js/Blast.js animations

Referencing a solution shared on this forum: Velocity.js/Blast.js starting opacity at 0 I am currently working with Velocity.js and Blast.js to implement a basic word-by-word loading animation, commonly used. This setup also involves Cycle2. Additionally, ...

Issue with scroll down button functionality not functioning as expected

Is there a way to create a simple scroll down button that smoothly takes you to a specific section on the page? I've tried numerous buttons, jQuery, and JavaScript methods, but for some reason, it's not working as expected. The link is set up co ...

Analyzing cookie data and utilizing jQuery for data presentation

Let's brainstorm. I'm currently working on a chat bar and have successfully implemented its functionality. However, I am facing a challenge in maintaining the continuity of the chat boxes while navigating through different pages on the website. ...

Picture is not showing up on my MVC software

Within a table containing multiple other tds, I am having an image tag. <table class="MyClass"> <tr> <td> @Html.LabelFor(m => m.ShopName) </td> <td> @Html.TextBoxFor(mode ...

Guide on setting up create-next-app with version 12 instead of the latest version 13

For an upcoming Udemy course, I am required to develop a Next.js project. However, it specifically needs to be built using Next.js version 12 rather than the latest version 13. Does anyone know how I can achieve this? ...

GWT's Stylish Image Carousel

Can anyone recommend a simple image slider for GWT that meets the following requirements: Slides several images from right to left when user clicks on the image (selected image should be at the center) Has endless looping capability (the last image shoul ...

Retrieve a specific value from a JavaScript object

Utilizing the npm package app-store-scraper, I am extracting the app IDs of 1000 apps from the App Store. My objective is to retrieve the "id" field from each JavaScript object and save it in a .csv file. How can I accomplish this task? Below is the code ...

The removal of a JQuery element can result in causing the webpage to become unresponsive and lead to

When attempting to create a loop in JQuery to remove elements from my HTML, I encountered an issue where the function caused my browser to hang and become unresponsive. Here is the JQuery code I used: function removeElement(){ var i =0; ...

Creating a span element to replace the list item class in a JavaScript Modal Pop-up

I recently set up a portfolio website that showcases my projects. When you click on a project, a modal window opens with a carousel gallery inside. On my .html page, the projects are organized like this: <li class="Project" data-modal="myModal_1"> ...

In Vue js, where is the best place to incorporate something similar to a 'base.html' template?

My transition from a Flask backend without a front end framework to Vue.js (with no chosen backend yet) has me considering how to structure my project. Previously, I would create a 'base.html' file that contained all the necessary HTML code, depe ...

Locate the item within an array that contains the most keys

Can you help me with a coding challenge? I have an array of objects set up like this: let items = [ { a: '', b: 2, c: 3 }, { a: '', b: '', c: 5, d: 10 }, ...

Is there a way for Selenium-WebDriver to pause for a brief moment after using sendkeys?

I am currently developing a C# Selenium-WebDriver project. When sending keys, I need to pause for a few seconds afterwards. The code snippet below is what I have been using to wait for 2 seconds: public static void press(params string[] keys) { for ...

Having trouble using angular.isString in conjunction with ng-repeat

Is there a way to use angular.isString for comparison within an ng-if in an ng-repeat loop? Currently, all items in the array are being returned. I attempted to simply display the result of angular.isString, but no output is generated. This is my desired ...

Organizing Parsed JSON Data with JavaScript: Using the _.each function for Sorting

var Scriptures = JSON.parse( fs.readFileSync(scriptures.json, 'utf8') ); _.each(Scriptures, function (s, Scripture) { return Scripture; }); This code extracts and displays the names of each book from a collection of scriptures (e.g., Genesis, ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

React JS project experiencing issues with Material UI components not functioning properly

Here is a unique version of my app.js code: import React from "react"; import './App.css'; import {Button} from "@mui/material"; function App() { return ( <div className="App"> <h1>COVID-19 T ...