JavaScript排序项目,不包括某些特定项目 [英] Javascript sort items excluding some specific items

查看:47
本文介绍了JavaScript排序项目,不包括某些特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对某些项进行排序(对地图进行排序),我可以成功对其进行排序,但是我想根据其属性排除某些项

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

我想跳过基于 attr('product_id')的某些项目,因此不会基于列出的product_id进行排序,并且将首先返回.

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.

是否有一种方法可以根据ID等属性将某些项目排除在排序之外?

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

数据

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

推荐答案

您可以使用支票将所需项目排序在最前面,并返回支票的差额.

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

不止一个ID可以排序到顶部

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

这篇关于JavaScript排序项目,不包括某些特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆