2

Below is an example of my array of objects and I am supposed to sort these by name. The js normal sorting sorts as shown below, however my target is to sort by the numeric value, eg: "1 ex, 2 ex, 3 ex, 4 ex, 11 ex ..". Could someone help me how to achieve this?

[{id: 588, name: "1 ex"}
{id: 592, name: "11 ex"}
{id: 607, name: "2 ex"}
{id: 580, name: "3 ex"}
{id: 596, name: "4 ex"}]
user2004082
  • 141
  • 2
  • 8

5 Answers5

2

You have to include the parse function in your compare function like this:

var compare = function(a, b) {
  return parseInt(a.name) - parseInt(b.name);
}

console.log(x.sort(compare));
soupy-norman
  • 403
  • 2
  • 11
1

Split and convert the numeric part to integer using parseInt() then you can use those values to sort the records:

var arr = [{id: 588, name: "1 ex"},
{id: 592, name: "11 ex"},
{id: 607, name: "2 ex"},
{id: 580, name: "3 ex"},
{id: 596, name: "4 ex"}];

arr.sort(function (a, b) {
  var aNum = parseInt(a.name);
  var bNum = parseInt(b.name);
  return aNum - bNum;
});

console.log(arr);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

@user2004082, you can also try the below code to get the same as you want.

Try it online at http://rextester.com/GUPBC15345.

var arr = [{id: 588, name: "1 ex"},
{id: 592, name: "11 ex"},
{id: 607, name: "2 ex"},
{id: 580, name: "3 ex"},
{id: 596, name: "4 ex"}];

var map = {}
for(var item of arr) {
    map[item["name"]] = item;   
}

var arr = arr.map(function(item){return item["name"]}).sort(function(a, b){
    var a = parseInt(a.split(' ')[0]);
    var b = parseInt(b.split(' ')[0]);

    return a-b;
}).map(function(name){
    return map[name];
})

console.log(arr);

» Output

[ { id: 588, name: '1 ex' },
  { id: 607, name: '2 ex' },
  { id: 580, name: '3 ex' },
  { id: 596, name: '4 ex' },
  { id: 592, name: '11 ex' } ]
hygull
  • 8,464
  • 2
  • 43
  • 52
0

    arr = [{id: 588, name: "1 ex"},
    {id: 592, name: "11 ex"},
    {id: 607, name: "2 ex"},
    {id: 580, name: "3 ex"},
    {id: 596, name: "4 ex"}]
    
    result = arr.sort(function(a, b) { return parseInt(a.name) > parseInt(b.name) })
    console.log(result)
kiddorails
  • 12,961
  • 2
  • 32
  • 41
0

Try following

let arr = [{id: 588, name: "1 ex"},
{id: 592, name: "11 ex"},
{id: 607, name: "2 ex"},
{id: 580, name: "3 ex"},
{id: 596, name: "4 ex"}];

arr.sort((a,b) => a.name.split(" ")[0] - b.name.split(" ")[0]);

console.log(arr);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59