Sorting An array of objects

Sorting An array of objects

So for the past few days I've been trying to sort an array of objects while comparing the values I want to sort to a main array.

an array that contains standard elements

Let me put this straight, i.e. an array has five types of jewels ["beryl", "chrysoberyl", "corundum", "diamond", "feldspar"] and I want this to be a standard of sorting objects that'll have these jewels as values, I may want these to be in ascending order.

  • beryl = 1
  • chrysoberyl = 2
  • corundum = 3
  • diamond = 4
  • feldspar = 5

So it means all objects will be sorted according to the order of these jewels, let's take this array of objects as a sample.

let owners = [
    {name: 'Nolan', jewel: 'chrysoberyl'},
    {name: 'Bower', jewel: 'corundum'},
    {name: 'Ian', jewel: 'beryl'}
    ]

In my sorter function below i',m searching for the index of owners jewel in the jewels array then using the sort method to get the objects in ascending order.

 const sorter = (owners) =>{
        let jewels = ["beryl", "chrysoberyl", "corundum", "diamond", "feldspar"];
          return owners.sort((a, b) => jewels.indexOf(a.jewel) - jewels.indexOf(b.jewel))
    }

 console.log(sorter(owners))

And this is my sorted array:

[
  { name: 'Ian', jewel: 'beryl' },
  { name: 'Nolan', jewel: 'chrysoberyl' },
  { name: 'Bower', jewel: 'corundum' }
]

Thanks for reading.