-3

I have an array with key-value pairs, array columns are id and name. I want to sort this array by id.

The id column value is of type string type but I want to sort them as numeric values also should work on IE

Here is my code:

var items = [{
    "id": "165",
    "name": "a"
  },
  {
    "id": "236",
    "name": "c"
  },
  {
    "id": "376",
    "name": "b"
  },
  {
    "id": "253",
    "name": "f"
  },
  {
    "id": "235",
    "name": "e"
  },
  {
    "id": "24",
    "name": "d"
  },
  {
    "id": "26",
    "name": "d"
  }
];

console.log(items.sort((a, b) => Number(a.ID) - Number(b.ID)))

Though the order does change it doesn't change as expected also in IE an error is thrown.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Anshul
  • 25
  • 5
  • 4
    Have you tried anything. If so, please post your code. Stack Overflow is not a "write code for me" service. – Reinstate Monica Cellio Jul 03 '18 at 12:42
  • www.google.com for real now.. This kind of question is asked like EVERY day here, every goddamn day, you can surely find an answer in one of the previous ones – Dellirium Jul 03 '18 at 12:43
  • You can use sort function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Powkachu Jul 03 '18 at 12:43
  • 1
    item.sort((a, b) => Number(a.ID) - Number(b.ID)) I used but its not working on IE11. @Archer – Anshul Jul 03 '18 at 12:44
  • 1
    @Anshul "it's not working" is not very helpful. What isn't working? Please add more details to your question – Luca Kiebel Jul 03 '18 at 12:46
  • I am using angular 1 and I get a array of items shown above and want to show these items on UI according to ID column I use many codes using arrow (=> )for it but not working on IE11 only @Luca – Anshul Jul 03 '18 at 12:48

1 Answers1

2

Now you can do it with pure JS, using the sort method..

var items = [
  {
    "id": "165",
    "name": "a"
  },
  {
    "id": "236",
    "name": "c"
  },
  {
    "id": "376",
    "name": "b"
  },
  {
    "id": "253",
    "name": "f"
  },
  {
    "id": "235",
    "name": "e"
  },
  {
    "id": "24",
    "name": "d"
  },
  {
    "id": "26",
    "name": "d"
  }
];

items.sort((a,b)=>+a.id>+b.id);
console.log(items);
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37