简体   繁体   中英

Javascript custom sort, group certain items at bottom and sort within

In javascript, I have an array of items like so:

[
  'title',
  'firstname',
  'company',
  '[m]usr_phone'
  '[m]usr_city'
]

I would like to sort this using a custom array sort function so that all the non [m] items are sorted at the top, and all the [m] items are sorted and pushed to the bottom (after all the non [m] items)

To achieve this I tried a sort function like this:

function(a, b) {
            if (!a.indexOf('[m]') && b.indexOf('[m]') === 0
                || a.indexOf('[m]') && b.indexOf('[m]')) {
                    return -1;
            }

            if (a.indexOf('[m]') === 0 && !b.indexOf('[m]')) {
                return 1;
            }

            return 0;
        }

But couldn't get it to work properly. I would like the output to be:

[
  'company',
  'firstname',
  'title',
  '[m]usr_city'
  '[m]usr_phone'
]

Thanks for your help!

You could check the prefix and sort later by String#localeCompare .

 var array = ['title', 'firstname', 'company', '[m]usr_phone', '[m]usr_city']; array.sort(function (a, b) { return (a.slice(0, 3) === '[m]') - (b.slice(0, 3) === '[m]') || a.localeCompare(b); }); console.log(array);

You want to compare items in the same “class” (ie either starting with [m] or not) the same way, so use a.startsWith("[m]") == b.startsWith("[m]") to do this, and then use String#localeCompare .

 console.log([ "company", "firstname", "title", "[m]usr_phone", "[m]usr_city" ].sort((a, b) => { if (a.startsWith("[m]") == b.startsWith("[m]")) { return a.localeCompare(b); } else { return (a.startsWith("[m]") ? 1 : -1); } }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM