javascriptjqueryecmascript-6canjs

Javascript sort items excluding some specific items


I am trying to sort some items (sort a map) , I can sort it successfully, but I want to exclude some items based on it's attribute

Right now I am sorting like this based on attribute - price

 return (product.attr('active') !== 'f'
                }).sort(function(pA,pB){
                  return pB.attr('price') - pA.attr('price'); });

I want to skip some items based on attr('product_id') so the listed product_id's wont be sorted based, and will be returned first.

return (product.attr('active') !== 'f'
      }).sort(function(pA,pB){
   return pB.attr('price') - pA.attr('price'); }).except(pA.attr('product_id') == 5677));

Something like above, obviously except function does not exist.

Is there a way to exclude some items from sorting, based on it's attributes like id?

Data

Map
active
:
true
brand_id
:
1
categories
:
Map(2) ["All Products", "Snacks", _cid: ".map232", _computedAttrs: {…}, __bindEvents: {…}, _comparatorBound: false, _bubbleBindings: {…}, …]
channel_id
:
1
created
:
"2017-08-14T19:16:56.148029-07:00"
description
:
"Breakfast"
image
:
"/media/333807.png"
name
:
"Breakfast"
price
:
"1"
product_id
:
5677

Solution

  • You can sort the wanted item to front by using a check and return the delta of the check.

    var array = [{ product_id: 1, price: 1 }, { product_id: 2, price: 3 }, { product_id: 3, price: 4 }, { product_id: 4, price: 1 }, { product_id: 5, price: 8 }, { product_id: 5677, price: 1 }];
    
    array.sort(function (a, b) {
        return (b.product_id === 5677) - (a.product_id === 5677) || b.price - a.price;
    });
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    With more than just one id for sorting to top

    var array = [{ product_id: 1, price: 1 }, { product_id: 2, price: 3 }, { product_id: 3, price: 4 }, { product_id: 4, price: 1 }, { product_id: 5, price: 8 }, { product_id: 5677, price: 1 }];
        topIds = [5677, 2]
    
    array.sort(function (a, b) {
        return topIds.includes(b.product_id) - topIds.includes(a.product_id) || b.price - a.price;
    });
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }