gpt4 book ai didi

Javascript 排序项目排除某些特定项目

转载 作者:行者123 更新时间:2023-11-30 11:23:25 25 4
gpt4 key购买 nike

我正在尝试对一些项目进行排序(对 map 进行排序),我可以成功排序,但我想根据它的属性排除一些项目

现在我正在根据属性 - 价格这样排序

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

我想跳过一些基于 attr('product_id') 的项目,这样列出的 product_id 就不会被排序,并且会首先返回。

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

类似上面的东西,显然除了功能不存在。

有没有办法根据某些项目的属性(如 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

最佳答案

您可以使用支票将想要的项目排在前面,并返回支票的增量。

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可以排序到顶部

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 排序项目排除某些特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com