Home > other >  JavaScript -Get part of an element's string from an array
JavaScript -Get part of an element's string from an array

Time:07-28

I have this array

const array = ['item-30', 'part-12', 'list-41'];

What I need is to order these from smallest to largest based on the suffix of each element

Example:

  • part-12
  • item-30
  • list-41

As you can see from the list above the elements in the array array are showing up in order based on the suffix of the string (i.e. -12, -30, -40)

In addition I need the elements to be in order. BUT without the prefix in the string

Example:

  • part
  • item
  • list

So now the array is in order, minus the (-suffix).

I tried the following:

const array = ['item-30', 'part-12', 'list-41'];
console.log(array.sort((a, b) => a < b ? 1 : 1));

I really hope this makes sense. :D

CodePudding user response:

sort, map, split are used to solve this.

const fruits = ['item-30', 'part-12', 'list-41'];
var result = fruits.sort((a, b) => Number(a.split("-")[1]) - Number(b.split("-")[1])).map(a => a.split("-")[0])
console.log(result)

CodePudding user response:

When sort()ing numbers, the callback is simply a - b. To get these numbers we will .slice(-2) the last two characters of each string then coerce that string into a number by prefixing them with a :

.sort((a, b) =>  a.slice(-2) -  b.slice(-2))

Next, .map() each string and on each iteration .replace() a literal: - and "one or more digits": \d on the current string with nothing: '':

.map(x => x.replace(/-\d /, '')); 

let array = ['item-30', 'part-12', 'list-41'];
let output = array
  .sort((a, b) =>  a.slice(-2) -  b.slice(-2))
  .map(x => x.replace(/-\d /, '')); 
console.log(output);

  • Related