skip to Main Content

I don’t know if it’s possible. I’ve tried looking everywhere for an answer, but nothing.

const points = ["Apple - 40", "Orange - 80", "Lemon - 140"];

points.sort(function(a, b){return b-a});

I tried doing this, however it didn’t do anything.

3

Answers


  1. Your current sort() logic is attempting to coerce the strings to numeric values. As they begin with alphabetic characters, that’s not going to work as you expect.

    To do what you require you need to manually extract the digits and sort those directly. There’s a lot of ways to do this. In the example below I used a regex to remove anything that’s not a digit, but other approaches may work better for the format of string available in your specific use case.

    const points = ["Apple - 40", "Orange - 80", "Lemon - 140"];
    const getNumber = str => +(str.replace(/^D+/g, ''));
    
    let sortedPoints = points.sort((a, b) => getNumber(b) - getNumber(a));
    console.log(sortedPoints);
    Login or Signup to reply.
  2. You can write a custom function for comparison like following

    const points = ["Apple - 40", "Orange - 80", "Lemon - 140"];
    
    points.sort(function(a, b){
        let numberA = a.split(' - ')[1];
        let numberB = b.split(' - ')[1];
        return numberB - numberA;
    });
    

    It gets the number from the string and compares them instead of comparing the whole string.

    Login or Signup to reply.
  3. For the best performance just use String#lastIndexOf() to find the last space and slice the number:

    const points = ["Apple - 40", "Orange - 80", "Lemon - 140"];
    const getNumber = str => str.slice(str.lastIndexOf(' ') + 1);
    
    let sortedPoints = points.sort((a, b) => getNumber(b) - getNumber(a));
    console.log(sortedPoints);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search