IBazz
1
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]
-
(4) [{…}, {…}, {…}, {…}]
-
0: {colour: “stainless steel”}
-
1: {colour: “red black and silver”}
-
2: {colour: “Stainless steel”}
-
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
IBazz
3
Thank you very much Pullo.
I’ll lookup that article you posted a link to.
system
Closed
4
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.