Skip to content
Advertisement

How to sort according to the alphabet objects inside an object in Javascript

I have the next object:

ctrl.items

this object contains other objects:

items: {
    OBJ1: {
        label: 'banana'
    },
    OBJ2: {
        label: 'apple'
    },
    OBJ3: {
        label: 'cat'
    }
}

In the UI, I display the label of each object under items as part of a list. I would like this list to be sorted by the alphabet so the list will be: apple banana cat

So my expected object after the sorting should be

  items: {
        OBJ1: {
            label: 'apple'
        },
        OBJ2: {
            label: 'banana'
        },
        OBJ3: {
            label: 'cat'
        }
    }

How can I do it? I tried all kinds of sort example and nothing worked. for example I tried:

 ctrl.items.sort((a,b) => (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0));

Advertisement

Answer

items is an object, not an array, so you cannot use .sort on it.

However, you can convert an object into array by using Object.entries(items)

Below is an example:

let items = {
    OBJ1: {
        label: 'banana'
    },
    OBJ2: {
        label: 'apple'
    },
    OBJ3: {
        label: 'cat'
    }
}

// to be used by `Array.sort()`
function compare(a, b) {
    return a < b ? -1 
         : a > b ?  1
         : 0
}

// convert from object to key-value pair array
let entries = Object.entries(items)

// take out the keys
let keys = entries.map(entry => entry[0])

// take out the values
let values = entries.map(entry=>entry[1])

// store the value by label
values.sort((a,b) => compare(a.label, b.label))

// rebuild the object from the original keys and sorted values
let result = Object.fromEntries((keys.map((key,i) => [key, values[i]])))

/* 
result will be:
{
  OBJ1: { label: 'apple' }, 
  OBJ2: { label: 'banana' }, 
  OBJ3: { label: 'cat' }
} 
*/

— Addition

I’m not sure about why are you storing the values in the asked format. You may store the values in an array as well. This way you can sort the array directly.

For example:

let labels = [ 'banana', 'apple', 'cat' ]

labels.sort()

// the labels is now [ 'apple', 'banana', 'cat' ]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement