我正在使用Javascript,并具有以下对象数组:
const offersStep = [
{a: 1, price: 67.10},
{a: 3, price: 88.20},
{a: 5, price: 88.20},
{a: 7, price: 57.10},
{a: 13, price: 57.10},
{a: 15, price: 57.10},
{a: 29, price: 57.10},
{a: 30, price: 57.10},
]为了使存储在一个新的数组中,这些对象,忽略它--那些已经存储在新数组上的支柱price具有一个值的对象--我必须做什么和如何做呢?
预期产出:
offers = [
{a: 1, price: 67.10},
{a: 3, price: 88.20},
{a: 7, price: 57.10}
]发布于 2022-06-27 19:02:04
使用迭代来确定先前节省的价格是否与正在迭代的当前对象相匹配。
const offersStep = [
{a: 1, price: 67.10},
{a: 3, price: 88.20},
{a: 5, price: 88.20},
{a: 7, price: 57.10},
{a: 13, price: 57.10},
{a: 15, price: 57.10},
{a: 29, price: 57.10},
{a: 30, price: 57.10},
]
// Vars to store previously recorded prices.
var storedPrices = [];
// Var to store unique offersStep.
var uniqueOffersStep = [];
// Iterates through each of the offersStep array objects.
offersStep.forEach (function(value) {
// Sets a boolean to false .. used later to determine if the current object is added to the unique array.
var isSkip = false;
// Iterates through each of the storedPrices array.
storedPrices.forEach (function(spvalue) {
// If the current objects price matches one of the storedPrices then it sets the skip flag to true.
if (value.price == spvalue) {
isSkip = true;
}
})
// Adds the current objects price to the storedPrices array.
storedPrices.push(value.price);
// Check if the skip flag is still false after checking stored prices and adds the object to the uniqueOffers variable.
if (isSkip == false) {
uniqueOffersStep.push(value);
}
})
// Outputs the final var to console.
console.log(uniqueOffersStep);由于依赖于多个迭代层,因此对于较大的数据集来说,它的资源相当多。
希望这能有所帮助。
发布于 2022-06-27 18:33:32
您可以将对象存储在地图键中,该键从它的price中删除。在存储了唯一的价格之后,将地图的值()迭代器扩展到一个新的数组中,以获得结果。
const offersStep = [
{a: 1, price: 67.10},
{a: 3, price: 88.20},
{a: 5, price: 88.20},
{a: 7, price: 57.10},
{a: 13, price: 57.10},
{a: 15, price: 57.10},
{a: 29, price: 57.10},
{a: 30, price: 57.10},
];
function filterOffers(offers) {
let offersByPrice = new Map();
for (let offer of offers) {
if (!offersByPrice.has(offer.price)) {
// Store the offer
offersByPrice.set(offer.price, offer);
}
}
return [...offersByPrice.values()];
}
console.log(filterOffers(offersStep));
发布于 2022-06-27 18:39:58
Idea
过滤原始数组,通过一个集合来跟踪到目前为止遇到的价格。
码
const offersStep = [
{a: 1, price: 67.10},
{a: 3, price: 88.20},
{a: 5, price: 88.20},
{a: 7, price: 57.10},
{a: 13, price: 57.10},
{a: 15, price: 57.10},
{a: 29, price: 57.10},
{a: 30, price: 57.10}
];
let offer
, nset_prices = new Set()
;
offer = offersStep.filter ( po_item => {
let b_ok = !nset_prices.has(po_item.price)
;
if (b_ok) {
nset_prices.add(po_item.price)
}
return b_ok;
});
console.log(offer);
https://stackoverflow.com/questions/72776820
复制相似问题