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"}]
2

5 Answers 5

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));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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' } ]

Comments

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)

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.