Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - filter array of strings based on seperated ending

I have an array of strings like this:

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"
];

And I want to filter them so that only the ones that have the latest versions for the given "author:name" are left, thus removing ones that are not the latest (i.e. the "1.0.1" ones).

My expected result is this:

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

Any way to do this simply?

like image 895
Asineth Avatar asked Nov 07 '22 09:11

Asineth


1 Answers

You can do it with two loops first one find new ones second one check which is bigger

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);
like image 132
mr. pc_coder Avatar answered Nov 14 '22 21:11

mr. pc_coder