byCoder
byCoder

Reputation: 9184

JS: sort array by two fields

Now I have such code:

    sortArticles = (someArray) => {
        const result = [];

        let isValid = someArray.filter(item => item.isValid);
        let isInvalid = someArray.filter(item => !item.isValid);

        valid = funcSortArrayOfObjByKey(arrayChecked, 'article');
        invalid = funcSortArrayOfObjByKey(arrayUnchecked, 'article');
        // funcSortArrayOfObjByKey - is a function to sort, a kind of lodash implementation without unnecessary dependency 

        return result.concat(valid).concat(invalid);
    }

and I want to sort such array:

[
    {
        article: 'Some New Zarticle',
        isValid: false
    },
    {
        article: 'Some New Article',
        isValid: false
    },
    {
        article: 'Some New Zzarticle',
        isValid: true
    },
]

as result I want to see such array:

[
    {
        article: 'Some New Zzarticle',
        isValid: true
    },
    {
        article: 'Some New Article',
        isValid: false
    },
    {
        article: 'Some New Zarticle',
        isValid: false
    },
]

So: I need to have some kind of two arrays: first one, and second one (one with 'isValid', other without) and both of them should be sorted by 'article'. Is this possible to do somehow? I tried also this way:

someArray.sort((a, b) => {
  if (a.isValid === b.isValid) {
    return b.isValid - a.isValid;
  } else {
    return a.article.toLowerCase().localeCompare(b.article.toLowerCase());
  }
}) 

but it's not working as I want it...

Upvotes: 0

Views: 77

Answers (2)

sperjesi
sperjesi

Reputation: 11

I was able to use this method to sort your array based on isValid then article.

someArray.sort(function(a, b) {
    if (a.isValid === b.isValid) {
        return a.article.localeCompare(b.article);
    } else {
        return (a.isValid) ? -1 : 1;
    }
});

Upvotes: 0

Bergi
Bergi

Reputation: 664599

Your branches are inverted:

someArray.sort((a, b) => {
  if (a.isValid != b.isValid) {
//              ^^
    return b.isValid - a.isValid;
  } else {
    return a.article.localeCompare(b, undefined, { sensitivity: 'base' });
  }
}) 

Upvotes: 1

Related Questions