{
"order": [
{
"billDate": "1-apr-2016",
"stock": 2,
"Qty": 4,
"Amount": 4500,
"Available": '',
},
{
"billDate": "1-may-2016",
"stock": 3,
"Qty": 2,
"Amount": 4500,
"Available": '',
}
]
}
I have an array which is sorted by billDate . now i need to add my first Object date Stock (i.e 2) to next object Qty and add into Available field .
Expected Result:
{
"order": [
{
"billDate": "1-apr-2016",
"stock": 2,
"Qty": 5,
"Amount": 4500,
"Available": 0,
},
{
"billDate": "1-may-2016",
"stock": 3,
"Qty": 2,
"Amount": 4500,
"Available": 4,
}
]
}
First Object Stock is 2 and next object Qty is 2 so Available is 4.How to add like above approach ?
I have tried like this
var totalTaxes = order.reduce(function (sum, tax) {
return sum + (tax.Qty + tax.stock);
}, 0);
You don't want reduce for this at all. If your intention is to create an array of the same length with different values, you want map
const { order } = {"order":[{"billDate":"1-apr-2016","stock":2,"Qty":4,"Amount":4500,"Available":""},{"billDate":"1-may-2016","stock":3,"Qty":2,"Amount":4500,"Available":""}]}
const result = {
order: [
{...order[0], Available: 0}, // first entry with Available: 0
...order.slice(1).map((ord, i) => ({ // map the rest
...ord,
Available: ord.Qty + order[i].stock // calculate new Available
}))
]
};
console.log(result);
.as-console-wrapper { max-height: 100% !important; }
Related
I'm trying to compare this array of object :
"platforms": [
{
"id": 1,
"name": "KF",
"bankAccounts": [
{
"id": 22,
"balance": -100,
"lendingPlatformId": 3
},
{
"id": 27,
"balance": 500,
"lendingPlatformId": 4
}
],
},
{
"id": 3,
"name": "CC",
"bankAccounts": [
{
"id": 23,
"balance": 100,
"lendingPlatformId": 1
}
],
},
{
"id": 4,
"name": "DD",
"bankAccounts": [
{
"id": 28,
"balance": 0,
"lendingPlatformId": 1
}
],
}
]
I want to compare the platform[].id and match bankAccounts[].lendingPlatformId
for example:
bankAccounts[].id = 22, its lendingPlatformId = 3, so it need to find platform[].id = 3 and bankAccounts[].id = 23 and lendingPlatformId = 1 ,then compare their balance's sum is equal to zero, than push to new array.
expecting result is one new array:
isEqualToZero = [true, false, true, false]
(order is matter)
I'm thinking make it new object like:
platofmrId = 1 :{ lendingPlatformId: 3, balance:100 }, {lendingPlatformId: 4, balance:500 }
platofmrId = 3 :{ lendingPlatformId: 1, balance:-100 }
but seems it can't achieve what i want
i've no idea how to do it...
please help, Thanks!
const res=[] //to save result
platforms.forEach(platform=>{ //go through platforms
platform.bankAccounts.forEach(bank=>{ //go through platform bank account
// to get lendingPlatform
const lendPlatform=platforms.find(p=>p.id==bank.lendingPlatformId);
//add the balance and compare
if((lendPlatform.bankAccounts[0].balance+bank.balance)==0)
res.push(true) // if combined balance is zero
else
res.push(false)
})})
console.log(res)
const platforms = [
{
"id": 1,
"name": "KF",
"bankAccounts": [
{
"id": 22,
"balance": -100,
"lendingPlatformId": 3
},
{
"id": 27,
"balance": 500,
"lendingPlatformId": 4
}
]
},
{
"id": 3,
"name": "CC",
"bankAccounts": [
{
"id": 23,
"balance": 100,
"lendingPlatformId": 1
}
]
},
{
"id": 4,
"name": "DD",
"bankAccounts": [
{
"id": 28,
"balance": 0,
"lendingPlatformId": 1
}
]
}
];
const emptyArrayInit = Array.from(new Array(4), ()=>[0,0,0,0])
platforms.forEach(platform=>{
const {id, bankAccounts}=platform;
const index = id-1;
bankAccounts.forEach(bankAccount=>{
const {balance,lendingPlatformId } =bankAccount;
const lendingPlatformIdIndex = lendingPlatformId-1;
if(balance>0){
emptyArrayInit[index][lendingPlatformIdIndex] += balance;
}else{
emptyArrayInit[lendingPlatformIdIndex][index] += balance
}
})
})
console.log(emptyArrayInit,'emptyArrayInit');
/// [ [ 0, 0, 0, 500 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
it's simple to reach your goal.
const res=[] //to save result
platforms.map(platform=>{ //first loop
platform.bankAccounts.map(bank=>{ // inner loop bankaccounts
// to get lendingPlatforms
const lendPlatforms=platforms.find(p=>p.id==bank.lendingPlatformId);
//compare balance
if((lendPlatforms.bankAccounts[0].balance+bank.balance)==0)
res.push(true) // if combined balance is equal to zero
else
res.push(false)
})})
console.log(res)
I would need to check if the objects in the "food" array are equal to each other, and the ones that are - combine into one adding amount and mody.amount and leaving the rest unchanged. This is just for better order data displaying. I tried with lodash library and reduce but but I don't know exactly how to construct this function that nested objects(mody) adds values as well, and in case isEqual returns false keep the object while concurrently concatenating the identical ones.
What I tried:
obj1.reduce((prev, next) => _.isEqual(prev, next) ? {...prev, amount: prev.amount + next.amount} : next
Now it looks like that:
const food = [
{
"id": 1,
"name": "chicken",
"price": 6,
"amount": 1,
"mody": [
{
"id": 33,
"name": "cheese",
"price": 1,
"amount": 1
},
{
"id": 34,
"name": "chips",
"price": 2,
"amount": 1
}
]
},
{
"id": 1,
"name": "chicken",
"price": 6,
"amount": 1,
"mody": [
{
"id": 33,
"name": "cheese",
"price": 1,
"amount": 1
},
{
"id": 34,
"name": "chips",
"price": 2,
"amount": 1
}
]
},
{
"id": 2,
"name": "pizza",
"price": 6,
"amount": 2,
"mody": [
{
"id": 12,
"name": "extra cheese",
"price": 2,
"amount": 1
}
]
}
]
and would need something like that:
const food = [
{
"id": 1,
"name": "chicken",
"price": 6,
"amount": 2,
"mody": [
{
"id": 33,
"name": "cheese",
"price": 1,
"amount": 2
},
{
"id": 34,
"name": "chips",
"price": 2,
"amount": 2
}
]
},
{
"id": 2,
"name": "pizza",
"price": 6,
"amount": 2,
"mody": [
{
"id": 12,
"name": "extra cheese",
"price": 2,
"amount": 1
}
]
}
]
The algorithm to sum the food amounts and mody amounts are almost the same, the difference is that for each food that has the same id we will sum the mody amount. To make the algorithm simpler I used a dictionary as the accumulator on the reduce function so we have a unique element per key. This element will be our final food or mody with the amount sum.
Mody sum algoritm:
const sumMody = (modyAccumulator, currentMody) => {
//Get the stored mody in the accumulator dictionary or null if it the mody is not stored
const storedMody = modyAccumulator[currentMody.id] ?? null
// if mody is null then add mody to the dictionary using its id as key
if (!storedMody) {
modyAccumulator[currentMody.id] = currentMody
} else {
//Mody is stored then sum amount
storedMody.amount += currentMody.amount
}
return modyAccumulator
}
The food sum algoritm is the same as the sumMody, the only difference is that it calls the sumMody function when the foods are equal:
const sumFood = (foodAccumulator, currentFood) => {
//Get the stored foodin the accumulator dictionary or null if it the food is not stored
const storedFood = foodAccumulator[currentFood.id] ?? null
// if food is null then add food to the dictionary using its id as key
if (!storedFood) {
foodAccumulator[currentFood.id] = currentFood
} else {
//Food is stored then sum food amount
storedFood.amount += currentFood.amount
//Create a list with mody from both foods
const modyList = [...storedFood.mody, ...currentFood.mody]
//Use reduce passing the sumMody callback function and initialize the accumulator with a dictionary
const modySumDictionary = modyList.reduce(sumMody, {})
/* The function above return a dictionary where the identifier is the mody.id
and the value is the mody. We only need the values from that dictionary so
we use Object.values to extract all the values. */
storedFood.mody = Object.values(modySumDictionary)
}
return foodAccumulator
}
To execute both sums:
//As explained before the reduce function will return a dictionary so we use Object.values to get only the values
const result = Object.values(food.reduce(sumFood, {}))
console.log(result)
Algoritm without comments:
const sumMody = (modyAccumulator, currentMody) => {
const storedMody = modyAccumulator[currentMody.id] ?? null
if (!storedMody) {
modyAccumulator[currentMody.id] = currentMody
} else {
storedMody.amount += currentMody.amount
}
return modyAccumulator
}
const sumFood = (foodAccumulator, currentFood) => {
const storedFood = foodAccumulator[currentFood.id] ?? null
if (!storedFood) {
foodAccumulator[currentFood.id] = currentFood
} else {
storedFood.amount += currentFood.amount
const modyList = [...storedFood.mody, ...currentFood.mody]
const modySumDictionary = modyList.reduce(sumMody, {})
storedFood.mody = Object.values(modySumDictionary)
}
return foodAccumulator
}
const result = Object.values(food.reduce(sumFood, {}))
console.log(result)
Reference to Object.values
How to get the array of objects based on condition in javascript.
I have array object obj in which each objects w1,w2...wn should have count greater than 2.
How to filter the array object based on object key in javascript.
function getObject (obj1){
var result = obj1.filter(e=> e.w1.count > 2 && e.w2.count > 2);
return result;
}
var output = this.getObject(obj1);
var obj1=[
{
"memberid": "s1",
"w1":{"count": 1, "qty": 1},
"w2":{"count": 0, "qty": 0},
... wn
"totalcount": 1
},
{
"memberid": "s2",
"w1":{"count": 2, "qty": 2, "amount": 400.0},
"w2":{"count": 1, "qty": 2, "amount": 503.0},
... wn
"totalcount": 5
},
{
"memberid": "s3",
"w1":{"count": 3, "qty": 2, "amount": 0.0},
"w2":{"count": 3, "qty": 4, "amount": 503.0},
... wn
"totalcount": 6
}
]
Expected Output:
[
{
"memberid": "s3",
"w1":{"count": 3, "qty": 2, "amount": 0.0},
"w2":{"count": 3, "qty": 4, "amount": 503.0},
... wn
"totalcount": 6
}
]
You can filter your array based on every value in each object either not being an object, or if it is an object, having a count greater than 2:
const obj1 = [{
"memberid": "s1",
"w1": {
"count": 1,
"qty": 1
},
"w2": {
"count": 0,
"qty": 0
},
"totalcount": 1
},
{
"memberid": "s2",
"w1": {
"count": 2,
"qty": 2,
"amount": 400.0
},
"w2": {
"count": 1,
"qty": 2,
"amount": 503.0
},
"totalcount": 5
},
{
"memberid": "s3",
"w1": {
"count": 3,
"qty": 2,
"amount": 0.0
},
"w2": {
"count": 3,
"qty": 4,
"amount": 503.0
},
"totalcount": 6
}
];
const out = obj1.filter(o => Object.values(o).every(v => typeof v != 'object' || v.count > 2));
console.log(out);
you need to iterate over the object keys, filtering out the invalid ones
function getObject(obj1) {
// filter
return obj1.filter(e =>
// based on the entries [key, value]
Object.entries(e)
// filter out entries where key is not a w followed by a number
.filter(val => val[0].match(/w\d+/))
// if every selected entry as a count > 2
.every(val => val[1].count > 2)
);
}
const obj1=[{memberid:"s1",w1:{count:1,qty:1},w2:{count:0,qty:0},totalcount:1},{memberid:"s2",w1:{count:2,qty:2,amount:400},w2:{count:1,qty:2,amount:503},totalcount:5},{memberid:"s3",w1:{count:3,qty:2,amount:0},w2:{count:3,qty:4,amount:503},totalcount:6}];
const output = this.getObject(obj1);
console.log(output)
docs of usefull functions :
Object.entries,
Array.filter,
Array.every
function getObject (obj1) {
var result = obj1.filter((e) => {
var isValid = false;
var i = 1;
while (e['w' + i]) {
if (e['w' + i].count > 2) {
isValid = true;
} else {
isValid = false;
break;
}
i++;
}
return isValid;
});
return result;
}
I have the below object which has array of objects. I want format this object to object of Array of arrays
var object1 = {
"Usa": [{
"period": "2018-11-03T00:00:00.000+0000",
"qty": 1
}, {
"period": "2018-11-04T00:00:00.000+0000",
"qty": 2
}],
"india": [
{
"period": "2018-19-03T00:00:00.000+0000",
"qty": 2
}, {
"period": "2018-19-04T00:00:00.000+0000",
"qty": 3
}
]
}
export const createDataPoint = (period, qty) => {
return [
Date.now(time),
Math.round((Math.random() * 100) * 2) / 2 + quantity,
];
};
export function createData(object1) {
let data = [];
let total = [];
Object.keys(object1).map(function(item, index) {
object1[item].map(function(item2, index2) {
data.push(createDataPoint(item2.period, item2.qty));
})
object1[item] = data
})
// console.log(object1)
return object1;
}
But the output is, in every array there are 4 arrays instead of 2 respective arrays. Which means in every array, i am getting total arrays of size 4.
Expected output is
var object1={
"Usa":[
["123245235",1],
["21423435",2]
],
"india":[
["234325436",2],
["23422464",3]
]
}
Just reassign each array to new mapped array
const createDataPoint = ({period, qty})=>{
// do your processing here, just returning period & qty for simplicity
return [period, qty]
}
Object.keys(data).forEach(k=>{
data[k] = data[k].map(createDataPoint);
})
console.log(data)
<script>
const data = {
"Usa": [{
"period": "2018-11-03T00:00:00.000+0000",
"qty": 1
}, {
"period": "2018-11-04T00:00:00.000+0000",
"qty": 2
}],
"india": [{
"period": "2018-19-03T00:00:00.000+0000",
"qty": 2
}, {
"period": "2018-19-04T00:00:00.000+0000",
"qty": 3
}
]
}
</script>
This is an alternative using the function Object.entries to get the entries as follow [country, array] and then with the function reduce build the desired output.
The function map will generate the array with tow indexes.
This approach doesn't mutate the original object
var object1={ "Usa":[ {"period": "2018-11-03T00:00:00.000+0000", "qty": 1 }, { "period": "2018-11-04T00:00:00.000+0000", "qty": 2 } ], "india":[ { "period": "2018-19-03T00:00:00.000+0000", "qty": 2 }, { "period": "2018-19-04T00:00:00.000+0000", "qty": 3 } ] },
result = Object.entries(object1).reduce((a, [country, arr]) => {
return Object.assign(a, {[country]: arr.map(({period, qty}) => [Date.now(period), qty])});
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Array.prototype.reduce & Object.entries:
var obj = { "Usa": [{ "period": "2018-11-03T00:00:00.000+0000", "qty": 1 }, { "period": "2018-11-04T00:00:00.000+0000", "qty": 2 }], "india": [{ "period": "2018-19-03T00:00:00.000+0000", "qty": 2 }, { "period": "2018-19-04T00:00:00.000+0000", "qty": 3 }] }
const result = Object.entries(obj)
.reduce((r, [k,v]) => (r[k] = v.map(({period, qty}) => [period, qty]), r),{})
console.log(result)
Somewhat simple approach can be done via Object.keys & reduce:
var obj = { "Usa": [{ "period": "2018-11-03T00:00:00.000+0000", "qty": 1 }, { "period": "2018-11-04T00:00:00.000+0000", "qty": 2 }], "india": [{ "period": "2018-19-03T00:00:00.000+0000", "qty": 2 }, { "period": "2018-19-04T00:00:00.000+0000", "qty": 3 }] }
const result = Object.keys(obj)
.reduce((r, c) => (r[c] = obj[c].map(({period, qty}) => [period, qty]), r),{})
console.log(result)
i wanted to move element in nested array. so, here this my data:
let products = [
{
"product_name": "A",
"_id": "5ace995c14a759325776aab1",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 100,
"price": 2000
},
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 80,
"price": 1500
},
]
},
{
"product_name": "B",
"_id": "5ace995914a759325776aab0",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f9b",
"qty": 80,
"price": 1500
}
],
}
]
The output that i expected:
[
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 100,
"price": 2000,
"product_name": "A",
},
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 80,
"price": 1500,
"product_name": "A",
},
{
"_id": "5ad3a274ac827c165a510f9b",
"qty": 80,
"price": 1500,
"product_name": "B",
}
]
then, my solve code:
function move() {
var result = []
for (product of products) {
for (transaction of product.transactions) {
transaction.product_name = product.product_name
result.push(transaction)
}
}
return result
}
product = move()
Is there any effective way to create the output, maybe with array map or anything else? Thank you.
You could flat the transactions with Array#reduce and using Object.assign for adding product_name.
Also used:
destructuring assignment for the properties and
short hand properties for taking a variable as property with the name as key.
var products = [{ product_name: "A", _id: "5ace995c14a759325776aab1", transactions: [{ _id: "5ad3a274ac827c165a510f99", qty: 100, price: 2000 }, { _id: "5ad3a274ac827c165a510f99", qty: 80, price: 1500 }] }, { product_name: "B", _id: "5ace995914a759325776aab0", transactions: [{ _id: "5ad3a274ac827c165a510f9b", qty: 80, price: 1500 }] }],
result = products.reduce((r, { transactions, product_name }) =>
r.concat(transactions.map(t => Object.assign({}, t, { product_name }))),
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can reduce and map the transactions to add the product name
let result = products.reduce((c,v)=>{ //Loop the array using reduce
let transactions = v.transactions.map(o=>{ //Loop thru each transactions using map
return Object.assign(o,{"product_name":v.product_name}); //Clone the transaction and add the property product_name
});
return c.concat(transactions); //Merge the current array and the transactions
},[]);
Here is a snippet:
//Your array
let products=[{"product_name":"A","_id":"5ace995c14a759325776aab1","transactions":[{"_id":"5ad3a274ac827c165a510f99","qty":100,"price":2000},{"_id":"5ad3a274ac827c165a510f99","qty":80,"price":1500},]},{"product_name":"B","_id":"5ace995914a759325776aab0","transactions":[{"_id":"5ad3a274ac827c165a510f9b","qty":80,"price":1500}],}]
//The short version
let result = products.reduce((c, v) => c.concat(v.transactions.map(o =>Object.assign(o, {"product_name": v.product_name}))), []);
console.log(result);
Just using js methods you can have your desired output
const products = [
{
"product_name": "A",
"_id": "5ace995c14a759325776aab1",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 100,
"price": 2000
},
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 80,
"price": 1500
},
]
},
{
"product_name": "B",
"_id": "5ace995914a759325776aab0",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f9b",
"qty": 80,
"price": 1500
}
],
}
]
let output =[];
products.forEach(elm => elm.transactions.forEach(transaction => {
transaction.product_name = elm.product_name;
output.push(transaction)}));
console.log(output);