javascript - sort array of strings by separated suffix

Here's an array of strings for reference:

const strings = [
  "author:app:1.0.0",
  "author:app:1.0.1",
  "author:app2:1.0.0",
  "author:app2:1.0.2",
  "author:app3:1.0.1"
];

I need to filter them so that only the latest versions for each "author:name" are retained, removing older ones (e.g., "1.0.1").

The expected result should look like this:

const filteredStrings = [
  "author:app:1.0.1",
  "author:app2:1.0.2",
  "author:app3:1.0.1"
];

Is there a simple way to achieve this?

Answer №1

If you want to accomplish this task, you'll need to utilize two separate loops. The first loop will help identify new elements, while the second loop will determine which element is larger.

const strings = [
  "author:app:1.0.0",
  "author:app:1.0.1",
  "author:app2:1.0.0",
  "author:app2:1.0.2",
  "author:app3:1.0.1"
];
filteredones = [];
strings.forEach(element => {
  var arr = element.split(":");
  var isnew = true;
  var found = filteredones.find(function(element2) {
    var x = element2.split(":");
    return x[1] == arr[1] && x[0] == arr[0]
  });
  if (found == undefined) {
    filteredones.push(element);
  }
});
for (var i = 0; i < filteredones.length; i++) {
  element = filteredones[i];
  var arr = element.split(":");
  var isnew = true;
  var found = strings.find(function(element2) {
    var x = element2.split(":");
    return x[1] == arr[1] && x[0] == arr[0] && x[2] > arr[2]
  });
  if (found != undefined) {
    filteredones[i] = found;
  }
};

console.log(filteredones);

Answer №2

To determine the most recent value in the string within each element of the array, analyze the last index and transfer those that meet the criteria to a separate array.

Answer №3

To efficiently manage key/version pairs, it is recommended to utilize an object for storage and later convert the data into a suitable output format. For version comparison, various methods can be implemented as outlined in this resource: How to compare software version number using js? (only number)

result = {};
for (var s of input) {
  // parts = ["author", "appname", "version"]
  var parts = s.split(":");
  var i = parts[0] + ":" + parts[1];
  if (!result[i] || compareVersion(parts[2], result[i]))
    // If not present or version is greater
    result[i] = parts[2]; // Add to result
}
result = Object.keys(result).map(k => k + ":" + result[k])

For a practical demonstration, you can refer to this working demo: https://codepen.io/bortao/pen/LYVmagK

Answer №4

Create an object with keys representing the app names.
The method getValue calculates the version value for comparison purposes. Update the object values when a newer version is detected (i.e., the value is greater).

const strings = [
  "author:app:1.0.0",
  "author:app:1.0.1",
  "author:app2:1.0.0",
  "author:app2:1.0.2",
  "author:app3:1.0.1"
];

const filter = data => {
  const res = {};
  const getValue = item =>
    item
      .split(":")[2]
      .split(".")
      .reduceRight((acc, curr, i) => acc + curr * Math.pow(10, i), 0);
  data.forEach(item => {
    const app = item
      .split(":")
      .slice(0, 2)
      .join(":");
    if (!res[app] || (app in res && getValue(item) > getValue(res[app]))) {
      res[app] = item;
    }
  });
  return Object.values(res);
};

console.log(filter(strings));

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

Retrieve a specific object by its name within a MapType() column in a PySpark dataframe

My PySpark dataframe has an interesting structure, where the array format starts with a number: 1: "item / state / zip" most of the time, but not always. The order can be different at times. data = [ ("Item A", "2024-12-01", {"1": "city: Palo Alto", "2 ...

What is the best way to keep the calendar of a Datepicker always visible while still being able to select a date easily?

When I write my code, the calendar only appears when I press the TextBox. I attempted to place the datepicker in a <div>, but then I was unable to retrieve the selected date. @model Plotting.Models.CalendarModel @using (Html.BeginForm("Calendar", "H ...

Displaying the Database Within an Array by Utilizing a Foreach Loop

I'm encountering an issue while attempting to utilize a foreach loop in order to display my database. I consistently receive an error message. What I aim to achieve is to output each row and column. Below is the snippet of my code: $sql = "SELECT a.* ...

sending an array of information to a shader in a threeJS environment

I am currently working on passing "volume._data" to my fragment shader in threeJS. This data is stored as a Float32Array and has a maximum of 512x512x512x4 elements. var mat = new THREE.ShaderMaterial({ uniforms: { color: {type: &apo ...

Exploring Java Arrays and the Concept of Inheritance

My understanding of array types being different classes has been challenged by the realization that reference type arrays are also considered objects of Object[] and their superclasses' array form. Is this interpretation correct? Take a look at the f ...

Utilizing Express middleware to handle asynchronous operations with next and Promises

Here is a very basic Express router with a handler: router.get('/users/:userId/roles/:roleId', function(req, res, next){ const roleId = req.params.roleId; res.rest.resource = UserModel.findOne({ _id: req.params.userId}).exec().then(funct ...

"Encountering a 404 error with the angular2-in-memory-web-api

Currently, I am in the process of developing a 5 minute application using Angular 2 with reference to this particular guide: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html. While working on the HTTP section, I encountered a 404 error due to the a ...

One method to add up the variances of each pair, and then total the results of each pair using nedb

In my nedb database called trades.json, I am simulating stock trades with the following data: {"buySell":"BUY","currentPrice":431.55,"_id":"GyTaUKVOCa9x5APS"}, {"buySell":"SELL","cu ...

Tips on ensuring that the Google Maps marker remains in the center as you drag the map with the AGM component

I've implemented AGM (Angular Google Maps) in my Ionic Project to showcase Google Maps, and I'm looking to have the marker stay centered on the map even when it is dragged. Is there a way to achieve this with AGM? Please let me know if I have mad ...

Error encountered while trying to retrieve the value following JSON parsing

I'm struggling with converting the value from the string below. I've attempted to parse it as JSON, but have had no success. const val1 = "{a: '123'}"; console.log(typeof(val1)); // string const a = JSON.parse(val1); // Error: Unexpe ...

Tips for integrating Angular 2 with different websites and modules while utilizing PHP as the backend

I am looking to transition to using more industry-standard practices by starting my front-end development with Angular 2 instead of my custom JS MVC-framework. However, I am encountering some challenges while working with Angular and would like to address ...

Utilizing jQuery: How to pass the $this object along with additional parameters to a

Is there a way to pass the value of this along with other parameters to a function? I have attempted the following methods, but they have not been successful: function update_alt($this, my_param){ this_alt = $(this).attr('alt'); ...

Vuetify - Issue "An extra loader may be required to manage the output of these loaders."

I am currently utilizing Materio Template Vuetify along with Babel. To begin, I serve the template by using yarn serve. Upon completion of the packaging process, I encountered several errors prompting me to include an additional loader. Here is the conte ...

"Encountering a bug with setting the pixel ratio in Three.js on IOS

I am currently working on a three.js website where I load a json file using ObjectLoader. Everything works perfectly on all platforms: Windows with all desktop browsers, and Android phones with all browsers. However, IOS (specifically iPad Air) is causing ...

Java Script error persisted in db.system.js.save within MongoDB encountered but remains unresolved

Hello all, I am fairly new to the world of mongoDB and I need some help with performing a search using js stored in mongoDB. Below you will find the javascript code that is stored in my mongoDB database. When attempting the query below: db.eval("dc(cough ...

Prevent access to the current window using JavaScript for a specified number of seconds

Currently working on a web application that utilizes backboneJs and nodeJS. I am seeking to prompt the user to refrain from closing the current window for a period of 10 seconds before granting them full control. Is it feasible to achieve this using Java ...

Find the identification number by searching through the text

I'm trying to find a way to retrieve the node id during a text search. Here's an example: http://jsfiddle.net/53cvtbv9/529/ I attempted using two methods to get the id of a node after the search: console.log($('#jstree').jstree(true). ...

Basic example of jQuery in an ASPX file

I can't figure out why this basic example is not working. In my WebApplication, I have a script: function myAlert() { $("#Button1").click(function () { alert("Hello world!"); }); } In my asp page, I have the following code: < ...

Is it feasible to trigger a dialog box by clicking on a textField within MaterialUI?

Is there a way to create a clickable textField that opens a dialog box for users to input more text? I'm specifically looking for a solution using MaterialUI. Currently, I have a workaround where a button is displayed to open the dialog box instead o ...

Encountered a problem while assigning a function to a variable

I'm currently working with a function that retrieves images based on a search query. Here's the code: function getImage(query){ var serach_title = query.replace(/\ /g, '+'); var imgUrl = "https://ajax.googleapis.com/ajax/s ...