Javascript sort items excluding some specific items

家住魔仙堡 提交于 2021-02-04 21:26:30

问题


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

回答1:


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; }


来源:https://stackoverflow.com/questions/48935830/javascript-sort-items-excluding-some-specific-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!