Skip to content
Advertisement

Using logical OR operator inside a loop to sort an array

I have an array like this:

JavaScript

That I am trying to sort based on name and size or color. This is defined like this:

JavaScript

I can do sorting like this:

JavaScript

But I dont know how to modify the sort so it sorts based on the values from var sorts – so a.size - b.size || a.color - b.color; will be dynamic based on the values from sorts – it can be based on name,size or name,size,color which will be added by || :

JavaScript

Advertisement

Answer

See Dynamically access object property using variable

You can access keys using a variable by using the bracket notation:

JavaScript

Furthermore, if your string is always comma separated, you can call String#split() to convert it into keys:

JavaScript

Before we continue, I have to point out that subtracting two values only works if you’re sorting numbers, not if you’re sorting strings. For example

JavaScript

If you want a more universal sorting, you can use the relation comparison operators < and > that works on numbers, strings, and some objects like dates. Keep in mind that you have to return three values, not just true and false. So with this in mind, it’s easy to create a generic comparison function:

JavaScript

Now with this, alongside Array#reduce() you can achieve dynamic sorting:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement