Please help me, I want merge difference 3 arrays to join with field _id. My arrays like that. I try to merge all array by _id but still work wrong and i have no idea please.
//array 1
let inventory =[
{ _id: '0001',
itemId: '0001',
onHandQty: 70,
avgCost: 9,
balanceAmount: 630,
},
{ _id: '0002',
itemId: '0002',
onHandQty: 70,
avgCost: 5,
balanceAmount: 350,
}
]
//array 2
let po =[
{
_id : "0002",
onHandPO : 10
},
{
_id : "0001",
onHandPO : 20
}
]
//array 3
let so =[
{
_id: "0001",
onHandSO: 2
},
{
_id: "0003",
onHandSO: 1
}
]
I want all array join by _id to become one array like that. This result I need.
let inventory =[
{ _id: '0001',
itemId: '0001',
onHandQty: 70,
avgCost: 9,
balanceAmount: 630,
onHandPO : 20,
onHandSO: 2
},
{ _id: '0002',
itemId: '0002',
onHandQty: 70,
avgCost: 5,
balanceAmount: 350,
onHandPO : 10
},
{ _id: '0003',
itemId: '0002',
onHandQty: 0,
avgCost: 0,
balanceAmount: 0,
onHandPO : 0
onHandSO: 1
}
]
You could flat all array, group them by the common value and assign all values to a single object. Then get the result.
var inventory = [{ _id: '0001', itemId: '0001', onHandQty: 70, avgCost: 9, balanceAmount: 630 }, { _id: '0002', itemId: '0002', onHandQty: 70, avgCost: 5, balanceAmount: 350 }],
po = [{ _id: "0002", onHandPO: 10 }, { _id: "0001", onHandPO: 20 }],
so = [{ _id: "0001", onHandSO: 2 }, { _id: "0003", onHandSO: 1 }],
result = _([inventory, po, so])
.flatten()
.groupBy('_id')
.map(values => _.assign({}, ...values))
.value();
console.log(_.sumBy(result, 'onHandSO')); // total of onHandSO
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Related
I have a object
let data1 =
{
_id: "61d576ecb87f099d033a1930",
name: 'Milk',
quality: 'premium',
price: 10,
quantity: 10,
bagSize: '10',
bagCount: 10,
status: 'Process',
sellerDetails: [ [Object] ],
image: '/uploads/milk.jpg'
}
and I have array of objects
let data2 = [
{
_id: "61d576ecb87f099d033a1930",
name: 'Milk',
quality: 'Premium',
price: 10,
quantity: 10,
bagSize: '10',
bagCount: 10,
status: 'Process',
sellerDetails: [ [Object] ],
image: '/uploads/premium.jpg'
},
{
_id: "61d576ecb87f099d033a1931",
name: 'Haldi',
quality: 'Eagle',
price: 10,
quantity: 10,
bagSize: '10',
bagCount: 10,
status: 'Process',
sellerDetails: [ [Object] ],
image: '/uploads/rai.jpg'
}
]
Now I want to filter out data1 value from data2 so the expected result after filter should be
let data2 = [
{
_id: "61d576ecb87f099d033a1931",
name: 'Haldi',
quality: 'Eagle',
price: 10,
quantity: 10,
bagSize: '10',
bagCount: 10,
status: 'Process',
sellerDetails: [ [Object] ],
image: '/uploads/rai.jpg'
}
]
I have tried,
function filteredData(data1,data2){
const filtered = data1._id !== data2._id
return filtered
}
const filteredArr = data2.filter(filteredData)
Also I have referred this
How can I acheive my expected result, am I doing something completely wrong ?
The following probably does what you want (untested).
Read up on the filter() documentation #: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
and map() #: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
data2.filter(el => {
return data1._id !== el._id;
}
How do I filter an array two give me the subset created by overlap of two ranges?
For example, suppose Here's my array with a bunch of objects:
const list = [{
id: 1,
price: "10",
weight: "19.45"
},{
id: 2,
price: "14",
weight: "27.8"
},{
id: 3,
price: "45",
weight: "65.7"
},{
id: 4,
price: "37",
weight: "120.5"
},{
id: 5,
price: "65",
weight: "26.9"
},{
id: 6,
price: "120",
weight: "19.3"
},{
id: 7,
price: "20",
weight: "45.7"
}]
Now I want to filter the above array of objects based on a range for two parameters price and weight.
let range = {
startPrice: 15,
endPrice: 60,
startWeight: 22.0,
endWeight: 70.5,
}
I want to filter my list with these range parameters which will return me an array with a subset of objects satisfying both the filter ranges. Hence, the output array should be:
filtered = [{
id: 3,
price: "45",
weight: "65.7"
},{
id: 7,
price: "20",
weight: "45.7"
}]
Because items with id: 3 and id: 5 satisfy the subset of both of the two ranges. How should my list.filter() function look like? Any help is greatly appreciated, thank you.
Note: I've used parseFloat because values are stored as a String. There are other ways to get a Number out of a String.
var list = [{"id":1,"price":"10","weight":"19.45"},{"id":2,"price":"14","weight":"27.8"},{"id":3,"price":"45","weight":"65.7"},{"id":4,"price":"37","weight":"120.5"},{"id":5,"price":"65","weight":"26.9"},{"id":6,"price":"120","weight":"19.3"},{"id":7,"price":"20","weight":"45.7"}];
var range = {
startPrice: 15,
endPrice: 60,
startWeight: 22.0,
endWeight: 70.5
};
var filtered=list.filter(
element=> {
var elementprice=parseFloat(element.price);
var elementweight=parseFloat(element.weight);
if(
elementprice>=range.startPrice &&
elementprice<=range.endPrice &&
elementweight>=range.startWeight &&
elementweight<=range.endWeight
) {
return true;
}
return false;
}
);
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You mean 3 and 7
Also you need to either remove the quotes or cast to number. Note a filter will expect a true or false to a Boolean test is enough. No if or else needed
const list = [{ id: 1, price: "10", weight: "19.45" }, { id: 2, price: "14", weight: "27.8" }, { id: 3, price: "45", weight: "65.7" }, { id: 4, price: "37", weight: "120.5" }, { id: 5, price: "65", weight: "26.9" }, { id: 6, price: "120", weight: "19.3" }, { id: 7, price: "20", weight: "45.7" }];
let range = { startPrice: 15, endPrice: 60, startWeight: 22.0, endWeight: 70.5, }
const res = list.filter(item =>
+item.price >= range.startPrice &&
+item.price <= range.endPrice &&
+item.weight >= range.startWeight &&
+item.weight <= range.endWeight);
console.log(res);
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I've an array of objects, what I want is to copy all the objects from that, but with specific properties not all the properties.
like for example I've this object named cart
cart = [
{ id: 1, name: 'makeup', price: 200, qty: 1 },
{ id: 2, name: 'gloves', price: 300, qty: 2 },
{ id: 3, name: 'sanitizer', price: 400, qty: 3 },
{ id: 4, name: 'book', price: 100, qty: 1 },
{ id: 5, name: 'hairs', price: 250, qty: 4 },
{ id: 6, name: 'soap', price: 50, qty: 5 },
{ id: 7, name: 'shampoo', price: 700, qty: 1 },
]
and I want to extract only the id and qty attributes to a new array of objects.
How do I do this.
I already tried
products=cart.map(prod=>prod.id, prod.qty)
but this doesn't seems to be working.
Thanks in advance to helping hands
You can Array.prototype.map() or Array.prototype.reduce() over the entire array and only return the values you want.
const cart = [
{ id: 1, name: 'makeup', price: 200, qty: 1 },
{ id: 2, name: 'gloves', price: 300, qty: 2 },
{ id: 3, name: 'sanitizer', price: 400, qty: 3 },
{ id: 4, name: 'book', price: 100, qty: 1 },
{ id: 5, name: 'hairs', price: 250, qty: 4 },
{ id: 6, name: 'soap', price: 50, qty: 5 },
{ id: 7, name: 'shampoo', price: 700, qty: 1 },
]
console.log( cart.map( elem => ({id:elem.id, qty : elem.qty})))
You need to iterate and return only the desired properties.
cart = [
{ id: 1, name: 'makeup', price: 200, qty: 1 },
{ id: 2, name: 'gloves', price: 300, qty: 2 },
{ id: 3, name: 'sanitizer', price: 400, qty: 3 },
{ id: 4, name: 'book', price: 100, qty: 1 },
{ id: 5, name: 'hairs', price: 250, qty: 4 },
{ id: 6, name: 'soap', price: 50, qty: 5 },
{ id: 7, name: 'shampoo', price: 700, qty: 1 },
]
const newcart = cart.map(item => {
return {id: item.id, qty: item.qty}
});
console.log(newcart)
You almost had it correct.
When using arrow functions without the brackets, whatever is put after the arrow function is returned.
So your code could look like this:
const products = cart.map(({ id, qty }) => ({ id, qty }));
We destructure the object in the arrow function and return it as a new object.
Make sure to have the round brackets around the value that you return. Otherwise javascript will see it as the body of a function instead of an object that is returned.
You can update your .map() method like this to acheive the desired result:
const cart = [{id:1,name:"makeup",price:200,qty:1},{id:2,name:"gloves",price:300,qty:2},{id:3,name:"sanitizer",price:400,qty:3},{id:4,name:"book",price:100,qty:1},{id:5,name:"hairs",price:250,qty:4},{id:6,name:"soap",price:50,qty:5},{id:7,name:"shampoo",price:700,qty:1}];
const products = cart.map(({id, qty}) => ({ id, quantity: qty }))
console.log(products)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Anyone can help me with merge difference two array and array json. You can check my below code and result that I want to check difference between arr and arr2
First Array
let arr=[ '124', '125', '126', '127' ]
Second Array
let arr2=[{
_id: '125',
itemId: '125',
onHand: 10,
inventoryValue: 70,
avgCost: 7
},
{
_id: '124',
itemId: '124',
onHand: 10,
inventoryValue: 50,
avgCost: 5
}
]
I want result like that
let arr3=['126', '127' ]
Just filter your arr based on whether arr2 does not include each value as an _id by using some:
let arr = ['124', '125', '126', '127']
let arr2 = [{
_id: '125',
itemId: '125',
onHand: 10,
inventoryValue: 70,
avgCost: 7
},
{
_id: '124',
itemId: '124',
onHand: 10,
inventoryValue: 50,
avgCost: 5
}
];
let arr3 = arr.filter(e => !arr2.some(({ _id }) => _id == e));
console.log(arr3);
Find the index of all the ids od arr2 in arr1 and splice them form arr1
let arr = ['124', '125', '126', '127'];
let arr2 = [{
_id: '125',
itemId: '125',
onHand: 10,
inventoryValue: 70,
avgCost: 7
},
{
_id: '124',
itemId: '124',
onHand: 10,
inventoryValue: 50,
avgCost: 5
}
];
arr2.forEach(function(element) {
var index = arr.indexOf(element._id);
if (index > -1) {
arr.splice(index, 1);
}
});
console.log(arr);
ordersList = [
[{
id: 1,
name: "chicken Burger",
sellPrice: 20,
buyPrice: 15,
qty: 5
}, {
id: 2,
name: "Beef Burger",
sellPrice: 22,
buyPrice: 16,
qty: 3
}, {
id: 3,
name: "Chicken Sandwich",
sellPrice: 15,
buyPrice: 13,
qty: 2
}
],
[{
id: 1,
name: "Beef Burger",
sellPrice: 22,
buyPrice: 16,
qty: 2
}, {
id: 2,
name: "Chicken Sandwich",
sellPrice: 15,
buyPrice: 13,
qty: 2
}
],
[{
id: 1,
name: "Chicken Sandwich",
sellPrice: 15,
buyPrice: 13,
qty: 20
}, {
id: 1,
name: "Beef Burger",
sellPrice: 15,
buyPrice: 13,
qty: 10
}
]
]
A new Objects should be created with item-title(key), (Total Quantity,
Total BuyPrice, and Total SellPrice)(value) from the given JSON DATA.The purpose of this question is to find how list comprehension, immutable state,functional style can be used to find the data given below.
example-{ 'chicken Burger': { totalQty: 5, buySumPrice: 75, sellSumPrice: 100 },
'Beef Burger': { totalQty: 15, buySumPrice: 210, sellSumPrice: 260 },
'Chicken Sandwich': { totalQty: 24, buySumPrice: 312, sellSumPrice: 360 } }
function getAll() {
var total = {};
ordersList.map(function(orders) {
orders.map(function(order) {
total[order.name] = total[order.name] ? ({
qty: (total[order.name]).qty + order.qty,
buySumPrice:(total[order.name]).buySumPrice + order.buyPrice*order.qty ,
sellSumPrice: (total[order.name]).sellSumPrice + order.sellPrice*order.qty
}) : ({
qty: order.qty,
buySumPrice: order.buyPrice*order.qty,
sellSumPrice: order.sellPrice*order.qty
});
});
});
return total;
}
Is it possible to removing the outer total {} by returning the constructed array from the maps. Also using reduce to do the calculation for summation.
You have a real bear of a problem here. I'm going to solve it using ES6 because it has a couple of tools that makes this kind of thing much easier. If you need the ES5, copy/paste this into babel or add a build step to your application.
const getData = ordersList => {
let merge = ({totalQty=0, buySumPrice=0, sellSumPrice=0}={}, {qty, buyPrice, sellPrice}) => ({
totalQty: totalQty + qty,
buySumPrice: buySumPrice + (qty * buyPrice),
sellSumPrice: sellSumPrice + (qty * sellPrice)
});
return ordersList.reduce((ys, xs) => {
xs.forEach(x => Object.assign(ys, {[x.name]: merge(ys[x.name], x)}));
return ys;
}, {});
};
let answer = getData(ordersList);
console.log(JSON.stringify(answer, null, "\t"));
Output
{
"chicken Burger": {
"totalQty": 5,
"buySumPrice": 75,
"sellSumPrice": 100
},
"Beef Burger": {
"totalQty": 15,
"buySumPrice": 210,
"sellSumPrice": 260
},
"Chicken Sandwich": {
"totalQty": 24,
"buySumPrice": 312,
"sellSumPrice": 360
}
}
Remarks:
The ugliest part of this problem is that the Arrays are nested. If you could afford to flatten the Array(Array(Object{})) structure to Array(Object{}), it would be a much nicer problem. However, that would require iterating through your list twice. For reasonably large inputs, that computational overhead could be a deal breaker.