1

I have an array of objects which I sort by 'category' key. Why in output I see not sorted like:

Category 1, Category 2 ... Category 12.

Maybe I'm wrong in sort method? I don't know reasons why is it so.

The same with sort by length param in another method but first I want to deal with this

let arr = [
    {
  id: 1,
  category: 'Category 1'
    },
    {
  id: 2,
  category: 'Category 2'
    },
 {
  id: 3,
  category: 'Category 3'
    },
 {
  id: 4,
  category: 'Category 4'
    },
    {
  id: 5,
  category: 'Category 5'
    },
 {
  id: 6,
  category: 'Category 6'
    },
    {
  id: 7,
  category: 'Category 7'
    },
 {
  id: 8,
  category: 'Category 8'
    },
 {
  id: 9,
  category: 'Category 9'
    },
    {
  id: 10,
  category: 'Category 10'
    },
 {
  id: 11,
  category: 'Category 11'
    },
    {
  id: 12,
  category: 'Category 12'
    }
]

const sort = (obj, key) => {
    return obj.sort((a, b) => {
        let _a = a[key],
            _b = b[key]
        return _a.localeCompare(_b)
    })
}

console.log(sort(arr, 'category'))
Marty
  • 534
  • 8
  • 24

0 Answers0