Filter object from array of objects - javascript

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;
}

Related

Remove duplicate keys and combine unique values in JavaScript array

I have an array containing a customer ID, value of transaction, and transaction ID for each transaction performed by the customer.
I have 20,000 transactions performed by 9,000 customers.
I want one customer ID, an array of all the prices per that customer ID, and an array of all the transaction Ids per customer ID.
Currently looks like this:
var transactionArray =
{
customerId: '1',
price: [ 100 ],
transactionID: ['00a13']
},
{
customerId: '2',
price: [ 200 ],
transactionID: ['00a14']
},
{
customerId: '1',
price: [ 700 ],
transactionID: ['00a15']
},
{
customerId: '2',
price: [ 1700 ],
transactionID: ['00a16']
},
... 19996 more items
and I'd like it to look like this:
var customerArray =
{
customerId: '1',
price: [ 100, 700 ],
transactionID: ['00a13', '00a15']
},
{
customerId: '2',
price: [ 200, 1700 ],
transactionID: ['00a14', '00a16']
},
...8998 more items
Just using reduce and push the elements onto the array
var transactionArray = [{
customerId: '1',
price: [100],
transactionID: ['00a13']
},
{
customerId: '2',
price: [200],
transactionID: ['00a14']
},
{
customerId: '1',
price: [700],
transactionID: ['00a15']
},
{
customerId: '2',
price: [1700],
transactionID: ['00a16']
},
]
var results = Object.values(transactionArray.reduce((custs, { customerId, price, transactionID }) => {
var customer = custs[customerId]
if (!customer) {
custs[customerId] = {
customerId: customerId,
price: [...price],
transactionID: [...transactionID]
}
} else {
customer.price = [...customer.price, ...price]
customer.transactionID = [...customer.transactionID, ...transactionID]
}
return custs
}, {}))
console.log(results)
It's convenient that customerId's are integers. If that ever changes, then you will need to index them, then rebuild the object.
// create a separate array for holding order of customerIds
const customerIds = []
const result = transactionArray
.reduce((acc, { customerId, price, transactionID }) => {
const idIndex = customerIds.indexOf(customerId)
// check if customerId exists in customerIds array
if (idIndex < 0) {
// if it doesn't, add it to the customerId's array
customerIds.push(customerId)
// then add the matching price and transactionID to the accumulator
// of this reduce, spreading the contents of the array into 2 new arrays.
acc.push([[...price], [...transactionID]])
} else {
// if the customerId is already accounted for, then
// add the price and transactionID to that customer's bucket
// at the same index where the customerId exists inside customerIds
acc[idIndex][0].push(...price)
acc[idIndex][1].push(...transactionID)
}
return acc
}, [])
// finally, convert the arrays back into objects
.map((value, index) => {
return ({
customerId: customerIds[index],
price: value[0],
transactionID: value[1],
})
})
console.log(result)
which logs:
[
{
customerId: '1',
price: [ 100, 700 ],
transactionID: [ '00a13', '00a15' ]
},
{
customerId: '2',
price: [ 200, 1700 ],
transactionID: [ '00a14', '00a16' ]
}
]
If the customerIds were strings that didn't represent integers, this will still work -- for example, if your customer data looked like this:
const transactionArray = [
{
customerId: '324asdrea',
price: [ 100 ],
transactionID: ['00a13']
},
{
customerId: '4hdffgi2',
price: [ 200 ],
transactionID: ['00a14']
},
{
customerId: '324asdrea',
price: [ 700 ],
transactionID: ['00a15']
},
{
customerId: '4hdffgi2',
price: [ 1700 ],
transactionID: ['00a16']
}
]
which results in:
[
{
customerId: '324asdrea',
price: [ 100, 700 ],
transactionID: [ '00a13', '00a15' ]
},
{
customerId: '4hdffgi2',
price: [ 200, 1700 ],
transactionID: [ '00a14', '00a16' ]
}
]

how to merge find difference array and array json javascript?

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);

merge 3 array and join field in lodash?

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>

Mongodb aggregate push with index value of array

I am stucked in one aggregate query, Following is my data
Let database = [
{
_id: 'fefesf', name: 'John', info: {date: ISODate(), marks: '12'}
},
{
_id: 'uiuioo', name: 'John', info: {date: ISODate(), marks: '15'}
},
{
_id: 'erygbo', name: 'Ben', info: {date: ISODate(), marks: '18'}
}]
and my aggregate query is
var query = [{
$group: {
_id: '$name',
Marks: {
$push: {
x: '$index', ..............(not working right now)
y: '$info.marks'
}
}
}
}]
Is it possible to get index of grouped document as 'x' while pushing it in 'Marks' array. Like Output should be
[
{_id: 'John', Marks: [{x: 1, y: 12}, {x: 2, y: 15}]},
{_id: 'Ben',{x: 1, y: 18}}
]
Thanks in advance.!
Since mongoDB version 3.6 you can use $reduce for that*:
db.collection.aggregate([
{
$group: {
_id: "$name",
Marks: {$push: {y: "$info.marks"}}
}
},
{$project: {
Marks: {
$reduce: {
input: "$Marks",
initialValue: [],
in: {$concatArrays: [
"$$value",
[
{
y: "$$this.y",
x: {$add: [{$size: "$$value"}, 1]}
}
]
]
}
}
}
}
}
])
See how it works on the playground example
*Inspired by this answer

Filter and combine fields from 2 arrays with ES6 JavaScript?

I have 2 arrays, one of pizza details and the other is an order state. The id field is what links them. So in this example, the order has 2 x Pepperoni and 3 x Margarita.
const pizzaContent = [
{
id: 0,
name: 'Pepperoni',
price: 20,
hot: true,
stockQuantity: 3
},
{
id: 1,
name: 'Margarita',
price: 25,
stockQuantity: 3
},
{
id: 2,
name: 'Hawaiian',
price: 15,
stockQuantity: 0
}
];
const orders = [{
id: 0,
quantity: 2
},{
id: 1,
quantity: 3
}];
I'm trying to create a new array which has the quantity from orders and the fields from pizzaContent. Any pizzas which aren't in the order shouldn't be part of this array.
I've gotten close with the following:
const pizzasInOrder = this.props.orders.map(order => {
return (
{
quantity: order.quantity,
pizza: this.props.pizzas.find(pizza => {
return (
order.id === pizza.id
);
})
}
)
});
However, the result is:
pizzasInOrder = [
{
pizza: {id: 0, name: "Pepperoni", price: 20, hot: true, stockQuantity: 3},
quantity:2
},
{
pizza: {id: 1, name: "Margarita", price: 25, stockQuantity: 3},
quantity:3
}
]
But what I need is:
pizzasInOrder = [
{
id: 0, name: "Pepperoni", price: 20, hot: true, stockQuantity: 3, quantity: 2
},
{
id: 1, name: "Margarita", price: 25, stockQuantity: 3, quantity: 3
}
]
Use Object.assign and no extra keys
const pizzasInOrder = this.props.orders.map(order =>
Object.assign({quantity: order.quantity},
this.props.pizzas.find(pizza => order.id === pizza.id))
);
You can use Object.assign() to merge objects into one.
example..
const pizzaContent = [
{
id: 0,
name: 'Peperoni',
price: 20,
hot: true,
stockQuantity: 3
},
{
id: 1,
name: 'Margarita',
price: 25,
stockQuantity: 3
},
{
id: 2,
name: 'Hawian',
price: 15,
stockQuantity: 0
}
];
const orders = [{
id: 0,
quantity: 2
},{
id: 1,
quantity: 3
}];
let pizzasInOrder = orders.map((order) => {
return Object.assign(order,
pizzaContent.find(pizza => order.id === pizza.id));
});
console.log(pizzasInOrder);

Categories