0

my question is simple but I haven't found an answer yet.

I have this array:

        myArray = [
        {
            id: '123',
            color: 'red'
        },
        {
            id: '234',
            color: 'blue'
        },
        {
            id: '345',
            color: 'red'
        },
        {
            id: '456',
            color: 'yellow'
        }
        ]

I'd like to order this array to have the ones with "color: 'red'" at first and keep the other ones in the same order. I want it to be:

        myArray = [
        {
            id: '123',
            color: 'red'
        },
        {
            id: '345',
            color: 'red'
        },
        {
            id: '234',
            color: 'blue'
        },
        {
            id: '456',
            color: 'yellow'
        }
        ]

I tried using Angular's $filter and found a way to do it like this:

$filter('orderBy')(myArray, function(records) {
            return records.color !== 'red';
        });

I found this solution just playing around but I don't really understand why this works. I believe there should be a better and understandable solution.

Thanks!

1 Answer 1

4

The reason that works is that false is less than true in javascript therefore the reds will come before the rest.

Another way to solve this problem would be to have a function on your scope that can be used by the orderBy filter:

$scope.redsFirst = function(record){
    return record.color !== 'red';
}

And in the view:

ng-repeat='record in records | orderBy:redsFirst'

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.