0

i am fetching data and trying to sort it by name but it is not working, data that i am getting is

category: [
        {
            "_id": "6450a80c9b20c90c7b26c0c3",
            "name": "Mobiles",
            "__v": 0
        },
        {
            "_id": "6450ace4c2adca0b72717108",
            "name": "Electronics",
            "__v": 0
        }
    ]

and my code is

[...res.data.category].sort((a, b) => {
             return a.name - b.name;
           })
  • 2
    The subtraction operator is for numbers, not strings. What you want is `return a.name.localeCompare(b.name);` probably. – Pointy May 09 '23 at 11:53
  • Related: [How to sort strings in JavaScript](https://stackoverflow.com/q/51165) – VLAZ May 09 '23 at 12:25

1 Answers1

0

You should use localCompare

const arr = [
  {
    _id: '6450a80c9b20c90c7b26c0c3',
    name: 'Mobiles',
    __v: 0,
  },
  {
    _id: '6450ace4c2adca0b72717108',
    name: 'Electronics',
    __v: 0,
  },
];

// [
//     { _id: '6450ace4c2adca0b72717108', name: 'Electronics', __v: 0 },
//     { _id: '6450a80c9b20c90c7b26c0c3', name: 'Mobiles', __v: 0 }
// ]
console.log(arr.sort((a, b) => a.name.localeCompare(b.name)));

wonderflame
  • 6,759
  • 1
  • 1
  • 17