-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.

6
  • 4
    Have you tried anything. If so, please post your code. Stack Overflow is not a "write code for me" service. Commented Jul 3, 2018 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 Commented Jul 3, 2018 at 12:43
  • You can use sort function. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 3, 2018 at 12:43
  • 1
    item.sort((a, b) => Number(a.ID) - Number(b.ID)) I used but its not working on IE11. @Archer Commented Jul 3, 2018 at 12:44
  • 1
    @Anshul "it's not working" is not very helpful. What isn't working? Please add more details to your question Commented Jul 3, 2018 at 12:46

1 Answer 1

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);

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

9 Comments

That's a sick one liner :)
Arrow functions don't work in IE
You are right arrow not working on IE @Andrew Bone
Then don't use Arrow functions, they aren't needed here
items.sort(function(a, b){return +(a.id)>+(b.id)}) should work in IE
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.