javascript - How to sort an object based on string - Stack Overflow

I have an object like this from which I need to sort by id.64: {id: "83", name: "(83) x&

I have an object like this from which I need to sort by id.

64: {id: "83", name: "(83) x"}
65: {id: "84", name: "(84) y"}
66: {id: "85", name: "(85) z"}
67: {id: "86", name: "(86) a"}
68: {id: "9", name: "(9) b"}

I have checked many examples and I have tried them all but nothing worked for me

I tried this one first:

obj.sort((a, b) => {
            return a.id > b.id;
        })

Then,

obj.sort((a,b) => (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0));

Can anybody please help?

I have an object like this from which I need to sort by id.

64: {id: "83", name: "(83) x"}
65: {id: "84", name: "(84) y"}
66: {id: "85", name: "(85) z"}
67: {id: "86", name: "(86) a"}
68: {id: "9", name: "(9) b"}

I have checked many examples and I have tried them all but nothing worked for me

I tried this one first:

obj.sort((a, b) => {
            return a.id > b.id;
        })

Then,

obj.sort((a,b) => (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0));

Can anybody please help?

Share Improve this question asked Mar 22, 2019 at 4:46 user1687891user1687891 8644 gold badges16 silver badges32 bronze badges 8
  • What is the current result of your sort? Also, you must subtract your values in a sort to actually sort them, so you should probably change them to numbers – Andria Commented Mar 22, 2019 at 4:48
  • @ChrisBrownie55 the result is same as above – user1687891 Commented Mar 22, 2019 at 4:48
  • Try parsing the id while sorting? (parseInt) – zerosand1s Commented Mar 22, 2019 at 4:50
  • 3 You have strings, not numbers. Coerce them: obj.sort((a,b) => (+a.id > +b.id) ? 1 : ((+b.id > +a.id) ? -1 : 0));. Or simply obj.sort((a, b) => +a.id - +b.id);. – Gerardo Furtado Commented Mar 22, 2019 at 4:51
  • 1 Wait, you are trying to sort an object? Objects aren't index based – wentjun Commented Mar 22, 2019 at 4:59
 |  Show 3 more ments

5 Answers 5

Reset to default 3

You don't need to force -1, 1 and 0 results, because if result is negative, order will maintain and if it positive it will swap, so you can just subtract them:

let arr = [{id: "83", name: "(83) x"},
    {id: "84", name: "(84) y"},
    {id: "85", name: "(85) z"},
    {id: "86", name: "(86) a"},
    {id: "9", name: "(9) b"}];
    
    
let resp = arr.sort((a, b) => parseInt(a.id) - parseInt(b.id));

console.log(resp);

So, something like this?

let op = [{id: "83", name: "(83) x"},
    {id: "84", name: "(84) y"},
    {id: "85", name: "(85) z"},
    {id: "86", name: "(86) a"},
    {id: "9", name: "(9) b"}].sort((a,b) => {
        const nA = Number(a.id);
        const nB = Number(b.id);

        return (nA > nB) ? 1 : ((nB > nA) ? -1 : 0)
    });
    
console.log(op)

When you pare "83" to "9", you're paring strings. Just like "Alfred" es before "Zac" just because of the first letter, "83" es before "9" just because of the first letter.

Note: As you can see from different answers and ments, your sorting function is a bit wordy. You can simplify by returning something like this nA - nB instead of the whole (nA > nB) ? 1 : ((nB > nA) ? -1 : 0). Or you can even make it a single line function with coercion . There are a couple of answers here that use coercion, if you go that route you should accept one of their answers

Please see this short solution

obj.sort((a,b) => +a.id-+b.id)

I have an alternative solution to the methods which are mentioned over here.

First, we convert the object to array. Next, we have to provide a custom sorting function. We sort it by making use of localeCompare, and passing the numeric: true option to localeCompare. I have left the locale as undefined, but you may pass in your own locale options, depending on your use case.

const obj = {
  64: {id: "83", name: "(83) x"},
  65: {id: "84", name: "(84) y"},
  66: {id: "85", name: "(85) z"},
  67: {id: "86", name: "(86) a"},
  68: {id: "9", name: "(9) b"}
}

const result = Object.values(obj).sort((a,b) => {
  return a['id'].localeCompare(b['id'], undefined, {numeric: true});
});

console.log(result);

If you would prefer to squeeze everything onto one line,

const result = Object.values(obj).sort((a,b) => a['id'].localeCompare(b['id'],undefined, {numeric: true}));

Please read up more about JavaScript's sort method, as I have noticed that you are trying to 'directly' sort an object/dictionary using JavaScript's sort. It has to be in array format.

Your id is string so convert it to int in order to sort it . Use parseInt instead .

var obj=[{id: "83", name: "(83) x"},{id: "84", name: "(84) y"},{id: "85", name: "(85) z"},{id: "86", name: "(86) a"},{id: "9", name: "(9) b"}];
obj.sort((a, b) => {
            return parseInt(a.id )> parseInt(b.id);
        });
        
console.log(obj);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745566107a4633403.html

相关推荐

  • javascript - How to sort an object based on string - Stack Overflow

    I have an object like this from which I need to sort by id.64: {id: "83", name: "(83) x&

    16小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信