0

I used following function for sorting array.

var trArr = [{'Abc', 1}, {'ACd', 3}, {'Aab', 4}];

function compare(a,b) {
          if (a.name > b.name)
          {
              return -1;
          }
          if (a.name < b.name)
          {
              return 1;
          }

          return 0;
}

trArr.sort(compare);

result:

[{'ACd', 3}, {'Aab', 4}, {'Abc', 1}];

above result is due to capital 'C'

I need the following result:

[{'Aab', 4}, {'Abc', 1}, {'ACd', 3}];
1
  • 1
    .name.toLowerCase() Commented Feb 6, 2014 at 18:22

2 Answers 2

1

Try this

var trArr = [{
    name: 'Abc',
    id: 1
}, {
    name: 'ACd',
    id: 3
}, {
    name: 'Aab',
    id: 4
}];

function compare(a, b) {
    if (a.name.toLowerCase() < b.name.toLowerCase()) {
        return -1;
    }
    if (a.name.toLowerCase() > b.name.toLowerCase()) {
        return 1;
    }
    return 0;
}

trArr.sort(compare);
console.log(trArr)

DEMO

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

Comments

0

Try using toLowerCase

function compare(a, b) {
    if (a.name.toLowerCase() > b.name.toLowerCase()) {
        return -1;
    }
    if (a.name.toLowerCase() < b.name.toLowerCase()) {
        return 1;
    }
    return 0;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.