Difficulties sorting an array

Hi,

I am trying to sort an array but I can’t seem to grasp the concept.
I’d appreciate your help.

Here is the console display of the array

[code]

  1. (4) [{…}, {…}, {…}, {…}]

  2. 0: {colour: “stainless steel”}

  3. 1: {colour: “red black and silver”}

  4. 2: {colour: “Stainless steel”}

  5. 3: {colour: “stainless steel & black”}

[code]

I want to sort them alphabetically regardless of case.

Bazz

You’re trying to sort an array of objects.

This should do what you want:

const arr = [
  { colour: 'stainless steel' },
  { colour: 'red black and silver' },
  { colour: 'Stainless steel' },
  { colour: 'stainless steel & black' }
];

console.log(
  arr.sort( 
    (a, b) => a.colour.toLowerCase().localeCompare(b.colour.toLowerCase()) 
  )
);

Outputs:

[
  {colour: "red black and silver"},
  {colour: "stainless steel"},
  {colour: "Stainless steel"},
  {colour: "stainless steel & black"},
]

We have a decent article on this over on the main site (despite the currently borked code formatting).

1 Like

Thank you very much Pullo.

I’ll lookup that article you posted a link to.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.