how to merge find difference array and array json javascript? - 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);

Related

Filter object from array of objects

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

In JavaScirpt, how do I filter the elements of the same field in two arrays and return a new two-dimensional array

This is an example:
I want to regroup arry2 according to the fields in arry1
var arry1 = [
{id: 1, parentId: 0, name: "phone"},
{id: 2, parentId: 1, name: "nick"}
];
var arry2 = [
{id: 7, parentId: 0, name: "phone_item1"},
{id: 8, parentId: 1, name: "phone_item2"},
{id: 9, parentId: 0, name: "nick_item1"},
{id: 10, parentId: 1, name: "nick_item2"}
];
let newArrys = arry1.filter((item)=>{
return leve_two.indexOf(arry2.parentId) == -1
})
I want to return a two-dimensional array:
[[
{id: 7, parentId: 0, name: "phone_item1"},
{id: 9, parentId: 0, name: "nick_item1"}
],[
{id: 8, parentId: 1, name: "phone_item2"},
{id: 10, parentId: 1, name: "nick_item2"}
]]
I tried Array.filter and so on.
Can you help me?
You can use filter() method along-with Object.values() to get the desired output:
const arr1 = [
{id: 1, parentId: 0, name: "phone", level: 0, productCount: 0},
{id: 2, parentId: 1, name: "nick", level: 0, productCount: 0}
];
const arr2 = [
{id: 7, parentId: 0, name: "phone_item1", level: 1, productCount: 0},
{id: 8, parentId: 1, name: "phone_item2", level: 1, productCount: 0},
{id: 9, parentId: 0, name: "nick_item1", level: 1, productCount: 0},
{id: 10, parentId: 1, name: "nick_item2", level: 1, productCount: 0}
];
const filterIds = arr1.map(({ parentId }) => parentId);
const arr3 = Object.values(arr2.reduce((r, c) => {
r[c.parentId] = r[c.parentId] || [];
r[c.parentId].push(c);
return r;
}, {}));
console.log(arr3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
It looks just like grouping arry2 by parentId and arry1 looks useless 🤔
Use some lib for this. For example Ramda way:
const result = R.pipe(
R.groupBy(R.prop("parentId")),
R.toPairs,
R.map(R.last)
)(arry2)

Modifying values inside an array of objects

Let's say have an array of objects:
let A = [
{
id: 1,
item: 'item 1',
qty: 23,
unitPrice: 10;
totalAmount: qty*price,
},
{
id: 2,
item: 'item 2',
qty: 3,
unitPrice: 30,
totalAmount: qty*price,
}
];
I want to calculate the value totalAmount = qty * price. How do I do that for the whole list?
You can use map() and return the new object with all the previous properties and new property totalAmount
let arr = [ { id: 1, item: 'item 1', qty: 23, unitPrice: 10 }, { id: 2, item: 'item 2', qty: 3, unitPrice: 30, } ];
let res = arr.map(x => ({...x, totalAmout:x.unitPrice * x.qty}));
console.log(res)

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>

How to remove some elements in an object array using Lodash

I'll just ask on how to remove some elements in an object array using lodash.
var fruits = [
{ id: 1, name: 'Apple', price: 55, qty: 3, status: 'ripe' },
{ id: 2, name: 'Banana', price: 55, qty: 4, status: 'ripe' },
{ id: 3, name: 'Pineaple', price: 55, qty: 2, status: 'ripe' }
];
How will I remove the qty and status in all object array so it will look like this
[
{ id: 1, name: 'Apple', price: 55 },
{ id: 2, name: 'Banana', price: 55 },
{ id: 3, name: 'Pineaple', price: 55 }
]
Without any library, you can use map and destructure the object.
var fruits = [{"id":1,"name":"Apple","price":55,"qty":3,"status":"ripe"},{"id":2,"name":"Banana","price":55,"qty":4,"status":"ripe"},{"id":3,"name":"Pineaple","price":55,"qty":2,"status":"ripe"}]
var result = fruits.map(({qty,status,...r}) => r);
console.log(result);
You can do it without using a library too.
Use Array.map
var fruits = [{ id: 1, name: 'Apple', price: 55, qty: 3, status: 'ripe' },{ id: 2, name: 'Banana', price: 55, qty: 4, status: 'ripe' },{ id: 3, name: 'Pineaple', price: 55, qty: 2, status: 'ripe' }];
let result = fruits.map(({status,qty,...rest}) => rest);
console.log(result);
You can just iterate through the object using forEach and delete
the unwanted fields with the plain old delete operator.
This method cleans your current object, Without the need for a new object to be defined.
fruits.forEach((val) => {delete val.qty; delete val.status})
It is true that you don't need to use a library to effectively delete properties of an object though if you want to use lodash here is an example of how you would do that by using the .pick method:
let pickedFruits = [];
for (let i in fruits) {
pickedFruits.push(_.pick(fruits[i], ["id", "name", "price"]));
}
where pickedFruits will be the new array of objects each having an id, name and a price property.

Categories