Andrew
Andrew

Reputation: 389

Sorting Javascript Array with Split Function

I have an array that looks like this

var testArray = ['name1:13', 'name2:15', 'name3:13'];

I would like to sort the array by the number to the right of the colon.

So far I have this:

var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15

Upvotes: 0

Views: 2111

Answers (3)

kapil pandey
kapil pandey

Reputation: 1903

var testArray = ['name1:13', 'name2:15', 'name3:13'];
console.log(testArray.sort((a, b) => (a.split(":")[1] > b.split(":")[1]) ? 1 : -1))

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Split, convert to number and compare.

var testArray = ["name1:13", "name2:15", "name3:13"];

const sortFunction = (a, b) => {
  const value = str => Number(str.split(":")[1]);
  return value(a) - value(b);
};

testArray.sort(sortFunction);

console.log(testArray);

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370979

Make a helper function to access the [1]st index of the split result, then in the sort callback, call that function for both and return the difference:

var testArray = ['name1:13', 'name2:15', 'name3:13'];
const getVal = str => str.split(':')[1];
testArray.sort((a, b) => getVal(a) - getVal(b));
console.log(testArray);

Upvotes: 6

Related Questions