I'm working with Javascript, and have the following array of objects:
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},
]
What and How i have to do, in order to store in a new array, those objects, ignoring it those who the prop price
has a value who is already stored on the new array?
Expected output:
offers = [
{a: 1, price: 67.10},
{a: 3, price: 88.20},
{a: 7, price: 57.10}
]
You can store the objects in a Map keyed off its price
. After you have stored unique prices, spread the values() iterator of the Map into a new array to get your result.
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));
Idea
Filter the original array, keeping tabs on the prices encountered so far by means of a set.
Code
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);
Let me if the code works for you!
const offersStep = [
{ a: 1, price: 67.1 },
{ a: 3, price: 88.2 },
{ a: 5, price: 88.2 },
{ a: 7, price: 57.1 },
{ a: 13, price: 57.1 },
{ a: 15, price: 57.1 },
{ a: 29, price: 57.1 },
{ a: 30, price: 57.1 },
];
let tempOffers = {};
offersStep.forEach((eachObj) => {
const { price } = eachObj;
if (!tempOffers[price]) {
tempOffers[price] = eachObj;
}
});
const offers = Object.values(tempOffers);
console.log("offers are", offers);