Home > Back-end >  Sorting strings with matching endings JS
Sorting strings with matching endings JS

Time:01-31

Let's say I have an array with various strings in it:

let myArray = [
  "www.goal.com/kdñon-BigPussy", 
  "www.goal.com/qwñeorkfnvowv-Paulie", 
  "www.goal.com/woeknapffflmkub-Tony", 
  "www.goal.com/npylhyokhp-Silvio", 
  "www.goal.com/irjnfrfrn-Silvio"
];

As you see, every string ending is formatted like this: -Name.

What I want is to store the strings with the same ending (www.goal.com/npylhyokhp-Silvio and www.goal.com/irjnfrfrn-Silvio in our example) inside a new array.

How would you do it using JavaScript?

CodePudding user response:

You can use Array.prototype.filter() passing a testing function that implements String.prototype.endsWith() on each string in the array and returns true or false according the passed string as first argument.

let myArray = [
  "www.goal.com/kdñon-BigPussy", 
  "www.goal.com/qwñeorkfnvowv-Paulie", 
  "www.goal.com/woeknapffflmkub-Tony", 
  "www.goal.com/npylhyokhp-Silvio", 
  "www.goal.com/irjnfrfrn-Silvio"
];

const filteredArray = myArray.filter((url) => url.endsWith('Silvio'))

console.log(filteredArray);

CodePudding user response:

You could use String.lastIndexOf() to find where the name part of the URL starts:

const myArray = [
    "www.goal.com/kdñon-BigPussy",
    "www.goal.com/qwñeorkfnvowv-Paulie",
    "www.goal.com/woeknapffflmkub-Tony",
    "www.goal.com/npylhyokhp-Silvio",
    "www.goal.com/irjnfrfrn-Silvio"
];

const groupedByName = myArray.reduce((grouped, url) => {
    const name = url.substring(url.lastIndexOf("-")   1, url.length);
    grouped[name] = grouped[name] || [];
    grouped[name].push(url);
    return grouped;
}, {});

console.log(groupedByName);
const groups = Object.values(groupedByName);
console.log(groups);

  •  Tags:  
  • Related