3

I have an an array with key-value pair, 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.

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"
}
]
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Anshul
  • 61
  • 1
  • 7

5 Answers5

4
items.sort((a,b)=>a.id-b.id)
Manoj
  • 1,175
  • 7
  • 11
1

Use Arrays.sort()

var arr = [{"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"}];
arr.sort((a,b)=> Number(a.id) - Number(b.id));
console.log(arr);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
  • @Anshul ie doest not support arrow functions, replace arrow function write function(a,b). And please mark answer as accepted if it helped you – amrender singh Jul 03 '18 at 13:02
  • Yes you are right It is working after changing arrow to function(a,b). @amrender singh – Anshul Jul 05 '18 at 13:16
1

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) => Number(a.id) - Number(b.id));
console.log(items);
Joven28
  • 769
  • 3
  • 12
1
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"
}];

// for asscending
items.sort((a, b) => Number(a.id) - Number(b.id));
console.log(items);
// for descending
items.sort((a, b) => Number(b.id) - Number(a.id));
console.log(items);
nandal
  • 2,544
  • 1
  • 18
  • 23
0

The numeric strings can be compared in many ways. Suppose the strings are a and b,

  1. a-b
  2. parseInt(a) - parseInt(b) - Reference - Java Script parseInt
  3. +a - +b - Reference - Unary + operator to convert string to number
  4. Number(a) - Number(b) - Reference - Javascript Global Number Object

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(function(a,b){ return parseInt(a.id)-parseInt(b.id) }));
console.log(items.sort(function(a,b){ return a.id-b.id }));
console.log(items.sort(function(a,b){ return +a.id - +b.id }));
console.log(items.sort(function(a,b){ return Number(a.id)-Number(b.id) }));
Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42