简体   繁体   中英

Sort an array of objects based on a numeric key given as String

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"
}
]
items.sort((a,b)=>a.id-b.id)

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

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

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

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

  1. ab
  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) })); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM