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 numer
Solution 1:
items.sort((a,b)=>a.id-b.id)
Solution 2:
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);
Solution 3:
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);
Solution 4:
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);
Solution 5:
The numeric strings can be compared in many ways. Suppose the strings are a
and b
,
a-b
parseInt(a) - parseInt(b)
- Reference - Java Script parseInt+a - +b
- Reference - Unary+
operator to convert string to numberNumber(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){ returnparseInt(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){ returnNumber(a.id)-Number(b.id) }));
Post a Comment for "Sort An Array Of Objects Based On A Numeric Key Given As String"