How to sort and filter this array of hashes using underscore - javascript

I want to use underscore.js in order to take the highest price for each tokenId in the array of hashes below. I would imagine this would require running through the array twice, but perhaps there is a more efficient way. What's the best way to utilize underscore to only grab one hash keyed by tokenId and to select the one with the highest price with the fewest number of iterations through the entire array set?
const data = [
{
"tokenId": 1,
"price": 1.8
},
{
"tokenId": 1,
"price": 2.0
},
{
"tokenId": 1,
"price": 1.9
},
{
"tokenId": 2,
"price": 5.0
},
{
"tokenId": 2,
"price": 1.0
},
{
"tokenId": 3,
"price": 1.9
}
]
// final result should be
// sortedFiltered = [{tokenId: 1, price: 2.0}, {tokenId: 2, price: 5.0}, {tokenId: 3, price: 1.9}]

A reduce can do it in one iteration. Use the accumulator to keep max price values indexed by tokenId.
const data = [
{
"tokenId": 1,
"price": 1.8
},
{
"tokenId": 1,
"price": 2.0
},
{
"tokenId": 1,
"price": 1.9
},
{
"tokenId": 2,
"price": 5.0
},
{
"tokenId": 2,
"price": 1.0
},
{
"tokenId": 3,
"price": 1.9
}
]
// one iteration, with a custom function
const maxes = data.reduce((acc, o) => {
if (acc[o.tokenId] === undefined) acc[o.tokenId] = 0;
if (acc[o.tokenId] < o.price) acc[o.tokenId] = o.price;
return acc;
}, {});
console.log(maxes);

Related

Nested array issue in JavaScript

I have the following array
Array["MyArray",
{
"isLoaded":true,
"items":
[{
"id":"4",
"name":"ProductA",
"manufacturer":"BrandA",
"quantity":1,
"price":"25"
},{
"id":"1",
"name":"ProductB",
"manufacturer":"BrandB",
"quantity":5,
"price":"20"
}],
"coupons":null
}
]
I need to load product names and their quantity from the array.
const result = [key, value].map((item) => `${item.name} x ${item.quantity}`);
Here's one possible way to achieve the desired result:
const getProductsAndQuantity = ([k , v] = arr) => (
v.items.map(it => `${it.name} x ${it.quantity}`)
);
How to use it within the context of the question?
localforage.iterate(function(value, key, iterationNumber) {
console.log([key, value]);
const val2 = JSON.parse(value);
if (val2 && val2.items && val2.items.length > 0) {
console.log(val2.items.map(it => `${it.name} x ${it.quantity}`).join(', '))
};
});
How it works?
Among the parameters listed in the question ie, value, key, iterationNumber, only value is required.
The above method accepts the key-value pair as an array (of 2 elements) closely matching the console.log([key, value]); in the question
It uses only v (which is an object). On v, it accesses the prop named items and this items is an Array.
Next, .map is used to iterate through the Array and return each product's name and quantity in the desired/expected format.
Test it out on code-snippet:
const arr = [
"MyArray",
{
"isLoaded": true,
"items": [{
"id": "4",
"name": "ProductA",
"manufacturer": "BrandA",
"quantity": 1,
"price": "25"
}, {
"id": "1",
"name": "ProductB",
"manufacturer": "BrandB",
"quantity": 5,
"price": "20"
}],
"coupons": null
}
];
const getProductsAndQuantity = ([k, v] = arr) => (
v.items.map(
it => `${it.name} x ${it.quantity}`
)
);
console.log(getProductsAndQuantity());
I understood. You should learn about array methods such as map, filter, reduce. Here you go...
const items = [{
"id":"4",
"name":"ProductA",
"manufacturer":"BrandA",
"quantity":1,
"price":"25"
},{
"id":"1",
"name":"ProductB",
"manufacturer":"BrandB",
"quantity":5,
"price":"20"
}];
const result = items.map((item) => `${item.name} x ${item.quantity}`);
console.log(result);
I think I understand the question to say that the input is an array of objects, each containing an array of items. The key is that a nested array requires a nested loop. So, we iterate the objects and their internal items (see the lines commented //outer loop and // inner loop below)
Also, half-guessing from the context, it looks like the that the OP aims to assemble a sort of invoice for each object. First a demo of that, (and see below for the version simplified to exactly what the OP asks)...
const addInvoice = obj => {
let total = 0;
// inner loop
obj.invoice = obj.items.map(i => {
let subtotal = i.quantity * i.price;
total += subtotal
return `name: ${i.name}, qty: ${i.quantity}, unit price: ${i.price}, subtotal: ${subtotal}`
});
obj.invoice.push(`invoice total: ${total}`);
}
const objects = [{
"isLoaded": true,
"items": [{
"id": "4",
"name": "ProductA",
"manufacturer": "BrandA",
"quantity": 1,
"price": "25"
}, {
"id": "1",
"name": "ProductB",
"manufacturer": "BrandB",
"quantity": 5,
"price": "20"
}],
"coupons": null
}]
// outer loop
objects.forEach(addInvoice);
console.log(objects);
If my guess about the goal went to far, just remove the unit price, subtotal and total lines from the invoice function...
const objects = [{
"isLoaded": true,
"items": [{
"id": "4",
"name": "ProductA",
"manufacturer": "BrandA",
"quantity": 1,
"price": "25"
}, {
"id": "1",
"name": "ProductB",
"manufacturer": "BrandB",
"quantity": 5,
"price": "20"
}],
"coupons": null
}]
const summaryString = obj => {
return obj.items.map(i => `${i.name}, ${i.quantity}`);
}
const strings = objects.map(summaryString);
console.log(strings);

Getting multiple percentage from a reduce map of a json data

I would like to apologize in advance if there's already question like this but I've been searching all day and I really can find anything.
I call an api that returns a response. Then I only get the details/data that I need and currently now have a json file with this sample value:
{
"total": 563,
"shipping_fee": 58,
"e_charges": ???,
"order_items": [
{
"item_id": 6291020872,
"quantity": 1,
"price": 88,
"total": 88
},
{
"item_id": 7755274567,
"quantity": 1,
"price": 150,
"total": 150
},
{
"item_id": 7980571205,
"quantity": 1,
"price": 45,
"total": 45
},
{
"item_id": 12612977930,
"quantity": 1,
"price": 280,
"total": 280
}
]
}, ... {} {} {}....
My problem is that, I need to get the sum of all total in order_items [] then after that, I need to add the shipping_fee and get 2 sets of percentage
10%
8%
Note that, I'm getting the values in run-time.
const resDetails = await request.post(baseURL, {
data: viewData
});
info = await JSON.parse(JSON.stringify(await resDetails.json()));
This is where the json file came from:
orders = await info.data.orders.map((x) => (total: x.order_items.map(y => Number(y.order_price) * y.amount).reduce((total, y) => y+total),
shipping_fee : Number(x.shipping_fee),
e_charges: Number(Number((x.order_items.map(y=> Number(y.order_price) * y.amount).reduce((total, y) => Number(y+total)) + Number(x.shipping_fee)) * 0.1).toFixed()),
order_items: x.order_items.map((y) => ({
item_id : y.item_id,
quantity: y.amount,
price: Number(y.order_price),
total: Number(y.order_price) * y.amount)}))
I was able to get the 10% but my main problem is adding the other 8% without doing mapping, reducing and adding the shipping_fee again.
Number(Number((x.order_items.map(y=> Number(y.order_price) * y.amount).reduce((total, y) => Number(y+total)) + Number(x.shipping_fee)) * 0.1).toFixed())
I'm fairly new to the javascript/typescript world. I hope someone can help me find a more optimized way to achieve what I need. Thank you.
EDIT:
Here's the actual code:
You may please go through the below code. I'm not a big fan of doing map, reduce and calculations in single line because it takes away the readability. So, I broken down the calculations to a number of methods.
At the end, order total is calculated only once and saved the e_charges percentages in 2 different keys e_charges_8 and e_charges_10, which I believe you can modify as per your need.
let orders = [
{
"shipping_fee": 58,
"order_items": [
{
"item_id": 6291020872,
"quantity": 1,
"price": 88
},
{
"item_id": 7755274567,
"quantity": 1,
"price": 150
},
{
"item_id": 7980571205,
"quantity": 1,
"price": 45
},
{
"item_id": 12612977930,
"quantity": 1,
"price": 280
}
]
},
{
"shipping_fee": 58,
"order_items": [
{
"item_id": 6291020872,
"quantity": 1,
"price": 88
},
{
"item_id": 7755274567,
"quantity": 1,
"price": 150
},
{
"item_id": 7980571205,
"quantity": 1,
"price": 45
},
{
"item_id": 12612977930,
"quantity": 1,
"price": 280
}
]
}
]
const getOrderItemTotal = (orderItem) => {
return orderItem.quantity * orderItem.price
}
const getPercentage = (shippingFee, total, percentage) => {
return ((total + shippingFee) * percentage).toFixed()
}
const getOrderItemsTotal = (orderItems) => {
return orderItems.reduce((total, orderItem) => (total + orderItem.total), 0)
}
orders = orders.map(order => {
order.order_items.map(orderItem => {
orderItem.total = getOrderItemTotal(orderItem)
return orderItem
})
order.total = getOrderItemsTotal(order.order_items)
order.e_charges_8 = getPercentage(order.shipping_fee, order.total, 0.1)
order.e_charges_10 = getPercentage(order.shipping_fee, order.total, 0.08)
return order
})
console.log(orders)

How to use map() loop in javascript [duplicate]

This question already has answers here:
Why does a js map on an array modify the original array?
(5 answers)
Updating an array of objects without mutation
(1 answer)
Why does map mutate array of objects?
(3 answers)
Closed 3 years ago.
I have a structure like this:
let MainItem = [
{
"Id": "1",
"Cost": "1000"
},
{
"Id": "2",
"Cost": "5000"
},
{
"Id": "3",
"Cost": "2000"
},
{
"Id": "4",
"Cost": "3000"
}
];
I am going to change the value of Cost each of the elements with map() loop and store it in NewMainItem.
let NewMainItem = MainItem.map((item, i) => {
item.cost = item.cost + 1000
return item
});
console.log(MainItem)
console.log(NewMainItem)
The main problem is that by changing Cost in NewMainItem, the value of
Cost in MainItem will be changed too, but I don not want to do this. By using map() loop why the main object (MainItem ) will be changed too?
You should use map to create new objects from the existing ones, not modify them.
You could use the spread operator to create a new item like this:
{ ...item, Cost: parseFloat(item.Cost) + 100 };
Here parseFloat was used because the Costs values are set as string in your snippet. Feel free to change this as it fits your needs.
See below snippet:
let MainItem = [
{
"Id": "1",
"Cost": "1000"
},
{
"Id": "2",
"Cost": "5000"
},
{
"Id": "3",
"Cost": "2000"
},
{
"Id": "4",
"Cost": "3000"
}
];
let NewMainItem = MainItem.map((item, i) => {
return { ...item, Cost: parseFloat(item.Cost) + 100 };
});
console.log(MainItem)
console.log(NewMainItem)
You could assign a new object with the wanted changed value.
var mainItem = [{ Id: "1", Cost: "1000" }, { Id: "2", Cost: "5000" }, { Id: "3", Cost: "2000" }, { Id: "4", Cost: "3000" }],
newMainItem = mainItem.map(item => Object.assign({}, item, { Cost: +item.Cost + 1000 }));
console.log(mainItem);
console.log(newMainItem);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Using Javascript to isolate an object with an property larger than a given quantity, but smaller than the next object in sequence

In my JavaScript, I have an integer that represents an order quantity, and an object of all quantities offered:
{
"1": {
"quantity": 1,
"price": 10
},
"2": {
"quantity": 2,
"price": 20
},
"6": {
"quantity": 6,
"price": 50
},
"12": {
"quantity": 12,
"price": 80
}
}
I need to find the object with a quantity value greater than my order quantity, but smaller than the quantity value of the next object in the sequence.
For example, if my order quantity is 8, I need to isolate:
"6": {
"quantity": 6,
"price": 50
},
So I can get the correct price. I've tried various LoDash methods, but nothing seems to be quite right. Is there a way that I can achieve this?
You could take the keys and reverse the array and find the smaller or equal count.
function find(object, quantity) {
return Object.keys(object).reverse().find(v => v <= quantity);
}
var object = { 1: { quantity: 1, price: 10 }, 2: { quantity: 2, price: 20 }, 6: { quantity: 6, price: 50 }, 12: { quantity: 12, price: 80 } };
console.log(find(object, 8));
Based on your description, I'm assuming what you're trying to do is find the record corresponding to the lowest quantity higher than the input quantity. The example doesn't actually match that description though. If you're looking for the opposite (next largest, smaller than the input) you could flip the two inequalities.
some_prices = {
"1": {
"quantity": 1,
"price": 10
},
"2": {
"quantity": 2,
"price": 20
},
"6": {
"quantity": 6,
"price": 50
},
"12": {
"quantity": 12,
"price": 80
}
}
getNextQuantityPrice = (prices, quantity) => {
const largerQuantities = Object.values(prices)
.filter(value => value.quantity > quantity);
if (largerQuantities.length === 0) return null;
return largerQuantities
.reduce((min, next) => next.quantity < min.quantity ? next : min)
}
console.log(JSON.stringify(getNextQuantityPrice(some_prices, 2)));
If you just need to iterate through keys in a Javascript object, this has been answered many times.
var prices = {
"1": {
"quantity": 1,
"price": 10
},
"2": {
"quantity": 2,
"price": 20
},
"6": {
"quantity": 6,
"price": 50
},
"12": {
"quantity": 12,
"price": 80
}
};
for (qty in prices) {
// Do stuff
console.log(qty);
}
If you just need to tease out the quantities available (your object keys), use Object.keys(prices), which returns an array you can loop over.
Once the data are in an array, you can do another for loop, or start getting fancy with forEach(), filter(), and the like.
Like the other answers, I find the best way to deal with the basic question is to reverse the list. But rather than depending upon the original object being ordered the way you like, I think it's best to sort it up front, and then we can just do so in reverse order.
const nextQuantity = (quantities) => {
const reversed = Object .values (quantities) .sort (({quantity: q1}, {quantity: q2}) => q2 - q1)
return (requested) => reversed .find (({quantity}) => quantity < requested)
}
const quantities = {1: {quantity: 1, price: 10}, 2: {quantity: 2, price: 20}, 6: {quantity: 6, price: 50}, 12: {quantity: 12, price: 80}}
console .log (
nextQuantity (quantities) (8)
)
This also gives us a chance to store an intermediate function that doesn't need to reverse the list on every call. nextQuantity(quantities) returns a function you can call repeatedly with each requested quantity.
If you really want the output format from the question (that is, not just {quantity: 6, price: 50} but that result wrapped in a single-property object like {'6': {quantity: 6, price: 50}}) then you could rewrite it as
const nextQuantity = (quantities) => {
const reversed = Object .values (quantities) .sort (({quantity: q1}, {quantity: q2}) => q2 - q1)
return (requested) => {
const q = reversed .find (({quantity}) => quantity < requested)
return {[q.quantity]: q}
}
}
But I personally would find that format much harder to work with.

Group sum and transform json object with values in nested array

I am trying to aggregate and transform the following json :
[
{
"orderId" : "01",
"date" : "2017-01-02T06:00:00.000Z",
"items" : [
{
"itemId": 100,
"itemCost": 12,
"itemQuantity": 10
},
{
"itemId": 102,
"itemCost": 25,
"itemQuantity": 4
}
]
},
{
"orderId": "02",
"date" : "2017-01-08T06:00:00.000Z",
"items" : [
{
"itemId": 100,
"itemCost": 15,
"itemQuantity": 2
},
{
"itemId": 101,
"itemCost": 20,
"itemQuantity": 5
},
{
"itemId": 102,
"itemCost": 25,
"itemQuantity": 1
}
]
},
{
"orderId": "03",
"date" : "2017-02-08T06:00:00.000Z",
"items" : [
{
"itemId": 100,
"itemCost": 15,
"itemQuantity": 2
},
{
"itemId": 101,
"itemCost": 20,
"itemQuantity": 5
},
{
"itemId": 102,
"itemCost": 25,
"itemQuantity": 1
}
]
}]
into an object that is grouped by itemId, and then aggregated by quantity, and aggregated by total cost (item cost * item quantity for each order) by month. Example:
[
{
"itemId": 100,
"period": [
{
"month": "01/17",
"quantity": 12,
"cost": 130
}
]
},
{
"itemId": 101,
"period": [
{
"month": "01/17",
"quantity": 5,
"cost": 100
},
{
"month": "02/17",
"quantity": 5,
"cost": 100
}
]
},
{
"itemId": 102,
"period": [
{
"month": "01/17",
"quantity": 5,
"cost": 125
},
{
"month": "02/17",
"quantity": 1,
"cost": 25
}
]
}
]
I have a small indention on my desk in which I have been beating my head trying to figure how to do this using native map/reduce or lodash.
You can do like this:
var orders = [{orderId:"01",date:"2017-01-02T06:00:00.000Z",items:[{itemId:100,itemCost:12,itemQuantity:10},{itemId:102,itemCost:25,itemQuantity:4}]},{orderId:"02",date:"2017-01-08T06:00:00.000Z",items:[{itemId:100,itemCost:15,itemQuantity:2},{itemId:101,itemCost:20,itemQuantity:5},{itemId:102,itemCost:25,itemQuantity:1}]},{orderId:"03",date:"2017-02-08T06:00:00.000Z",items:[{itemId:100,itemCost:15,itemQuantity:2},{itemId:101,itemCost:20,itemQuantity:5},{itemId:102,itemCost:25,itemQuantity:1}]}];
// First, map your orders by items
var items = {};
orders.forEach(function(order) {
// set the month of each order
var month = new Date(order.date);
month = ('0' + (month.getMonth() + 1)).slice(-2) + '/' + String(month.getFullYear()).slice(-2);
// for each item in this order
order.items.forEach(function(item) {
// here we already have both keys: "id" and "month"
// then, we make sure they have an object to match
var id = item.itemId;
if (!items[id]) {
items[id] = {};
}
if (!items[id][month]) {
items[id][month] = { cost:0, quantity:0 };
}
// keep calculating the total cost
items[id][month].cost += item.itemCost * item.itemQuantity;
items[id][month].quantity += item.itemQuantity;
});
});
// Now, we format the calculated values to your required output:
var result = Object.keys(items).map(function(id) {
var obj = {
itemId: id,
period: Object.keys(items[id]).map(function(month) {
items[id][month].month = month;
return items[id][month];
}),
};
return obj;
});
console.log(result);
Hope it helps.
You could use this transformation:
const result = Object.values(myList.reduce( (acc, o) => {
const month = o.date.substr(5,2) + '/' + o.date.substr(2,2);
return o.items.reduce ( (acc, item) => {
const it = acc[item.itemId] || {
itemId: item.itemId,
period: {}
},
m = it.period[month] || {
month: month,
quantity: 0,
cost: 0
};
m.cost += item.itemCost * item.itemQuantity;
m.quantity += item.itemQuantity;
it.period[month] = m;
acc[item.itemId] = it;
return acc;
}, acc);
}, {})).map( o =>
Object.assign({}, o, { period: Object.values(o.period) })
);
const myList = [
{
"orderId" : "01",
"date" : "2017-01-02T06:00:00.000Z",
"items" : [
{
"itemId": 100,
"itemCost": 12,
"itemQuantity": 10
},
{
"itemId": 102,
"itemCost": 25,
"itemQuantity": 4
}
]
},
{
"orderId": "02",
"date" : "2017-01-08T06:00:00.000Z",
"items" : [
{
"itemId": 100,
"itemCost": 15,
"itemQuantity": 2
},
{
"itemId": 101,
"itemCost": 20,
"itemQuantity": 5
},
{
"itemId": 102,
"itemCost": 25,
"itemQuantity": 1
}
]
},
{
"orderId": "03",
"date" : "2017-02-08T06:00:00.000Z",
"items" : [
{
"itemId": 100,
"itemCost": 15,
"itemQuantity": 2
},
{
"itemId": 101,
"itemCost": 20,
"itemQuantity": 5
},
{
"itemId": 102,
"itemCost": 25,
"itemQuantity": 1
}
]
}];
const result = Object.values(myList.reduce( (acc, o) => {
const month = o.date.substr(5,2) + '/' + o.date.substr(2,2);
return o.items.reduce ( (acc, item) => {
const it = acc[item.itemId] || {
itemId: item.itemId,
period: {}
},
m = it.period[month] || {
month: month,
quantity: 0,
cost: 0
};
m.cost += item.itemCost * item.itemQuantity;
m.quantity += item.itemQuantity;
it.period[month] = m;
acc[item.itemId] = it;
return acc;
}, acc);
}, {})).map( o =>
Object.assign({}, o, { period: Object.values(o.period) })
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think the other answers out there do a pretty good job from the vanilla angle, so I wanted to take a stab at a more lodash-intensive approach since you mentioned it as a tag. This is mainly just a fun challenge, but I hope the solution is elegant enough for you to lift components from.
Before we begin, I'll be using both the vanilla lodash module and the functional programming flavor of lodash. Let fp be the functional programming module and _ be vanilla (and let orders be your original data structure). Also, as a challenge, I'll do my best to minimize vanilla JS methods and arrow funcs to maximize lodash methods and function creation methods.
First, let's get all the items in a row, paired with their order information:
const items = _.flatMap(orders, o=> _.map(o.items, i=> [i, o]));
I know I said I wanted to minimize arrow functions, but I couldn't think of any other way to get the order object to the end of the chain. Challenge yourself to rewrite the above in terms of a composition (e.g. fp.compose or _.flow) and see what happens.
I'd say now's as good a time as any to group up our pairs by the item id:
const id_to_orders = _.groupBy(items, fp.get('[0].itemId'));
Here, fp.get('[0].itemId') gives us a function which, given an array, returns the itemId of the first element (in our case, we have a list of pairs, the first element of which is the item, the second of which is the relevant order object). Therefore, id_to_orders is a map from an item's ID to a list of all the times it was ordered.
This id_to_orders map looks pretty close to the data structure we're after. At a high level, all that's left is transforming the order data for each item into the quantity and cost, grouped by month.
const result = _.mapValues(id_map, fp.flow(
// Arrange the item's orders into groups by month
fp.groupBy(month)
// We're done with the order objects, so fp.get('[0]') filters them
// out, and the second function pairs the item's cost and quantity
, fp.mapValues(fp.flow(
fp.map(fp.flow(fp.get('[0]'), i=> [i.itemCost, i.itemQuantity]))
// Sum up the cost (left) and quantity (right) for the item for the month
, fp.reduce(add_pair, [0, 0])))
// These last couple lines just transform the resulting data to look
// closer to the desired structure.
, _.toPairs
, fp.map(([month, [cost, count]])=> ({month, cost, count}))
));
And the helpers month and add_pair referenced above:
function month([item, order]){
const date = new Date(order.date)
, month = date.getMonth() + 1
, year = date.getFullYear().toString().slice(-2);
return `${month}/${year}`;
}
function add_pair(p1, p2){
return [p1[0] + p2[0], p1[1] + p2[1]];
}
Just out of curiosity (or sadism), let's see what this whole thing would look like chained together as a single pipeline:
const get_order_data = fp.flow(
fp.flatMap(o=> _.map(o.items, i=> [i, o]))
, fp.groupBy(fp.get('[0].itemId'))
, fp.mapValues(fp.flow(
fp.groupBy(month)
, fp.mapValues(fp.flow(
fp.map(fp.flow(fp.get('[0]'), i=> [i.itemCost, i.itemQuantity]))
, fp.reduce(add_pair, [0, 0])))
, _.toPairs
, fp.map(([month, [cost, count]])=> ({month, cost, count})))
));
const result = get_order_data(orders);
You'll notice this composed version has a lot more fp (as opposed to _). If you're curious why it's easier this way, I encourage you to read the lodash FP guide.
jsfiddle with everything.
Finally, if you'd like to transform the result from the code above exactly into the output format you mentioned in your post, here's what I recommend:
const formatted = _.keys(result).map(k=> ({itemId: k, periods: result[k]}));

Categories

Resources