2

Suppose I have an array:

["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"]

How could I sort the array such that the last numbers in each array element are in descending order? That is:

["Team B, 7, 1, 14","Team A, 6, 2, 12","Team C, 4, 4, 8"]

I have checked out various compare functions, but I cannot figure out how to tailor them to this specific situation.

3 Answers 3

4

Use a regex to get last digits in each string in Array#sort()

let reg = /\d+$/;

let arr = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];
arr.sort((a, b) => reg.exec(b) - reg.exec(a));

console.log(arr)

Sign up to request clarification or add additional context in comments.

Comments

2

You have to define your own compare function

var arr = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];
function compare(a,b){
  var vala = a.split(',').pop();
  var valb = b.split(',').pop();
  return valb-vala;
}
arr.sort(compare);
console.log(arr);

3 Comments

No need for parseInt(). Using - on 2 numeric strings casts each to number automatically
Thanks @charlietfl, I knew one thing from you
Or return b.split(',').pop() - a.split(',').pop() if you wanted a one-liner.
1

Basically, all you need to do is extract that last number, then use it in your comparason:

var myArray = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];

function sorter(item1, item2) {
    const split1 = item1.split(",");
    const split2 = item2.split(",");
    
    const num1 = split1[split1.length - 1] || 0;
    const num2 = split2[split2.length - 1] || 0;

    return num2 - num1; 
}

myArray.sort(sorter)
console.log(myArray)

2 Comments

or myArray.sort((item1, item2) => Number(item2.split(",").pop()) - Number(item1.split(",").pop()));
You can omit the Number() calls, because the - operator coerces both operands to numbers automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.