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)
Related
I have a quite complex json response which I have to combine, but im totally stuck. I didnt find a smart and effective way yet to detect all votedpositive matches of all users.
participants = {
"data": [
{
"userId": 2,
"votedPositive": [
{
"userId": 1
}
]
},
{
"userId": 3,
"votedPositive": [
{
"userId": 5
}
]
},
{
"userId": 4,
"votedPositive": []
},
{
"userId": 5,
"votedPositive": [
{
"userId": 2,
},
{
"userId": 3
}
]
},
{
"userId": 6,
"votedPositive": []
},
{
"userId": 7,
"votedPositive": []
},
{
"userId": 8,
"votedPositive": []
},
{
"userId": 9,
"votedPositive": []
},
{
"userId": 10,
"votedPositive": []
},
{
"userId": 11,
"votedPositive": []
},
{
"userId": 12,
"votedPositive": []
},
{
"userId": 1,
"votedPositive": [
{
"userId": 2
}
]
}
]
}
The output im expecting is a list or array with all the matching pairs. in the above example I would expect to get the information that userId 2 who voted userId 1 has a match because UserId 1 voted userId 2. Same goes for userId 3 and userId 5.
EDIT: This is what I have so far:
var participantsList = [];
for (var index = 0; index < participants.length; index++) {
for (var i = 0; i < participants[index]["votedPositive"].length; i++) {
participantsList.push([participants[index]["userId"], participants[index]["votedPositive"][i]["userId"]])
}
}
for (var index = 0; index < participantsList.length; index++) {
participantsList[index].sort(function (a, b) {
return a - b;
});
}
I created a list where im iterating based on the length of all the user ids and im pushing the userid and the voted id. After that I sorted the list so I can see duplicates now. Im not sure if it is working until here. The next step would be to filter out all duplicate combinations in another list, thats where im stuck right now.
The result I have right now is this:
[ [ 1, 2 ], [ 3, 5 ], [ 2, 5 ], [ 3, 5 ], [ 1, 2 ] ]
Create an object whose keys are the voters and values are a set of the users they voted for. Then you can go through this and find the pairs that voted for each other.
participants = {
"data": [{
"userId": 2,
"votedPositive": [{
"userId": 1
}]
},
{
"userId": 3,
"votedPositive": [{
"userId": 5
}]
},
{
"userId": 4,
"votedPositive": []
},
{
"userId": 5,
"votedPositive": [{
"userId": 2,
},
{
"userId": 3
}
]
},
{
"userId": 6,
"votedPositive": []
},
{
"userId": 7,
"votedPositive": []
},
{
"userId": 8,
"votedPositive": []
},
{
"userId": 9,
"votedPositive": []
},
{
"userId": 10,
"votedPositive": []
},
{
"userId": 11,
"votedPositive": []
},
{
"userId": 12,
"votedPositive": []
},
{
"userId": 1,
"votedPositive": [{
"userId": 2
}]
}
]
}
const votedFor = new Map();
participants.data.forEach(({
userId,
votedPositive
}) => {
if (!votedPositive.length) {
return;
}
if (!votedFor[userId]) {
votedFor.set(userId, new Set());
}
votedPositive.forEach(({
userId: target
}) =>
votedFor.get(userId).add(target)
);
});
const result = [];
votedFor.forEach((votees, voter) =>
votees.forEach(votee => {
if (votedFor.get(votee) && votedFor.get(votee).has(voter)) {
result.push([voter, votee]);
}
})
);
console.log(result);
the reason I need the code to work in core javascript is the tool we use, it uses Rhino from mozilla, so it cannot contain objects or methods related to manipulation of web pages.
I am trying to compare data from two json files using core javascript, When the order_number and extid is same we compare the count(fullfilments.line_items) and quantity(which is the sum of all the quantities of all line items under that fulfillment, fullfilments.line_items.quantity) . If the order_number and ext_id combination match along with count and sum above, do nothing. If no match, we remove the refund. the code works fine in Visual Studio. I am new to pentaho and I think the code needs to be changed as only core js works with this tool.
In the Orders file are sample json structure, for example Order_number (66 in this case) need to calculate and compare the count of line items(6 in this case) along with the Quantity of items(7 in this case), if it doesn't match need to remove Object Refund along with its elements, else No Changes.
``````Sample File````````
[
{
"app_id": 111,
"fulfillments":
[
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 66,
"ext_id": 110,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 398000,
"order_id": 450005,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 67,
"ext_id": 114,
"refunds": [
{
"id": 81,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 2
},
{
"id": 768,
"quantity": 2
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 68,
"ext_id": 113,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
}
]
```````````````````````````````json`````````````
//resultset file content
[
{
"order_number": 66,
"extid":110,
"line_items_count": 6,
"quantity": 7
},
{
"order_number": 67,
"extid":114,
"line_items_count": 4,
"quantity": 7
},
{
"order_number": 68,
"extid":113,
"line_items_count": 4,
"quantity": 6
}
]
`````````````````````````````````````````````````Code`````````````````
/**
* orders.json file has some sample orders
* resultset.json file has results from sql Lookup to the orders.
*
*/
const orders = require('./orders.json');
function compare(order) {
let isMatched = false;
let resultSet = require('./resultset.json');
let result = resultSet.find(function (item) {
return item.order_number === order.order_number;
});
if (
result &&
result.line_items_count === order.items &&
result.quantity === order.quantity
) {
isMatched = true;
}
return isMatched;
}
function fixOrders(orders) {
orders.map(function (order) {
let { order_number, line_items } = order;
let quantity = line_items.reduce(function (quantity, line_item) {
return (quantity += line_item.quantity);
}, 0);
if (!compare({ order_number, items: line_items.length, quantity })) {
delete order.refunds;
}
});
return orders;
}
let fixedOrders = fixOrders(orders);
console.log(fixedOrders);
// store in output.js
//========================================
// var fs = require('fs');
// fs.writeFile('outputFile.json', JSON.stringify(fixedOrders), (err) => {
// if (err) console.log(err);
// else {
// console.log('File written successfully\n');
// // console.log('The written has the following contents:');
// // console.log(fs.readFileSync('outputFile.json', 'utf8'));
// }
// });
[PDI Flow][1]
[1]: https://i.stack.imgur.com/3OzQE.png
In this array children array can have more childrens. I have a method in which I will get "lowValue" and "highValue". "Id" will be unique. when my method get called I need to use this unique id and replace old values of "lowValue" and "highValue" with the new ones. How can I do that?
// put your code here
<script>
myData = [{
"data": {
"name": "Applications",
"size": "200mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 1,
"name": "editor.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
}
},
{
"data": {
"id": 2,
"name": "settings.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
"mappedPersonaCount": 0,
}
}
]
},
{
"data": {
"name": "Cloud",
"size": "20mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 5,
"name": "backup-1.zip",
"highValue": 20,
"ratingID": 0,
"lowValue": 10
}
}]
}
]
</script>
Simple
const data = your_original_data
function replacer(lowValue, highValue, id){
for(let i = 0; i < data.length; i++){
for(let j = 0; j < data[i].children.length; j++){
if(data[i].children[j].data.id === id){
data[i].children[j].data.lowValue = lowValue
data[i].children[j].data.highValue = highValue
return
}
}
}
}
const myData = [{
"data": {
"name": "Applications",
"size": "200mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 1,
"name": "editor.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
}
},
{
"data": {
"id": 2,
"name": "settings.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
"mappedPersonaCount": 0,
}
}
]
},
{
"data": {
"name": "Cloud",
"size": "20mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 5,
"name": "backup-1.zip",
"highValue": 20,
"ratingID": 0,
"lowValue": 10
}
}]
}
]
const indexMap = new Map()
const parseDataToMap = (data = []) => {
data.forEach(e => {
if (e.children) {
e.children.forEach(e => {
indexMap.set(e.data.id, e.data)
})
}
})
}
parseDataToMap(myData)
console.log(myData[0].children[0].data)
const o = indexMap.get(1)
o.highValue = 25
o.lowValue = 11
console.log(myData[0].children[0].data)
Given the below-mentioned assumptions:
All children where id matches the supplied value will have the lowValue and highValue replaced.
The supplied id will always be present in the myData array in one or more children.
the following is one possible solution to achieve the desired result:
const replaceValues = (id = 5, lv = 5, hv = 50, arr = myData) => (
arr.reduce((f, i) => [...f, {
...i,
children: i.children.map(
child => ({
...child,
data: {
...child.data,
...(
child.data.id === id ? {
lowValue: lv,
highValue: hv
} : {}
)
}
})
)
}], [])
);
Explanation / Approach
The outer .reduce helps to iterate through the myData array
Each element in this array is placed as-is (using the ... spread operator)
Next, the children prop of each myData element is specified
Within this, i.children array is iterated using map to access each element
Each element here (again) is placed as-is using the ... spread-operator
Next, data is specified
Values for the data object are also spread (as before)
Then, if the data.id matches the parameter id then, lowValue and highValue are updated (using parameters lv and hv, respectively)
The ...( some_condition ? {k: v} : {} ) is one way to update an object's specific prop/s only when some_condition is true
Please use comments below to ask for further clarification/s.
Code Snippet
const myData = [{
"data": {
"name": "Applications",
"size": "200mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 1,
"name": "editor.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
}
},
{
"data": {
"id": 2,
"name": "settings.app",
"highValue": 20,
"ratingID": 0,
"lowValue": 10,
"mappedPersonaCount": 0,
}
}
]
},
{
"data": {
"name": "Cloud",
"size": "20mb",
"type": "Folder"
},
"children": [{
"data": {
"id": 5,
"name": "backup-1.zip",
"highValue": 20,
"ratingID": 0,
"lowValue": 10
}
}]
}
];
const replaceValues = (id = 5, lv = 5, hv = 50, arr = myData) => arr.reduce((f, i) => [...f, {
...i,
children: i.children.map(
child => ({
...child,
data: {
...child.data,
...(
child.data.id === id ? {
lowValue: lv,
highValue: hv
} : {}
)
}
})
)
}], []);
console.log('replace id: 5, low: 5, high: 50', replaceValues());
console.log('replace id: 1, low: 11, high: 21', replaceValues(1, 11, 21));
I have an array of objects that i need in a particular format. Currently it contains it's nested in such a way that it contains unwanted keys and container objects.
badArray = [
{
"college": {
"id": 1,
"location": "Victoria",
"rating": 10,
"alumni": [
{
"alumni_id": 1,
"alumni_position": 1
},
{
"alumni_id": 2,
"alumni_position": 3
},
]
}
},
{
"college": {
"id": 2,
"location": "New York",
"rating": 9,
"alumni": [
{
"alumni_id": 5,
"alumni_position": 7
}
]
}
}
]
What I'd like to get to is a less nested object with the following structure
goodArray = [
{
"id": 1,
"location": "Victoria",
"rating": 10,
"alumni": [
{
"alumni_id": 1,
"alumni_position": 1
},
{
"alumni_id": 2,
"alumni_position": 3
},
]
},
{
"id": 2,
"location": "New York",
"rating": 9,
"alumni": [
{
"alumni_id": 5,
"alumni_position": 7
}
]
}
]
I can remove the unwanted key using
Object.values(badArray[0])
But I'm really struggling to find a way to remove the unwanted outer container aswell.
Any help REALLY appreciated
You can just do an array map and return your desired array in this situation instead of trying to delete keys
badArray = [
{
"college": {
"id": 1,
"location": "Victoria",
"rating": 10,
"alumni": [
{
"alumni_id": 1,
"alumni_position": 1
},
{
"alumni_id": 2,
"alumni_position": 3
},
]
}
},
{
"college": {
"id": 2,
"location": "New York",
"rating": 9,
"alumni": [
{
"alumni_id": 5,
"alumni_position": 7
}
]
}
}
]
let goodArray = badArray.map(el => el.college)
console.log(goodArray)
Logic
Array.map through array.
Take Object.values of each Object in the array
Return the first value.
I have considered you have only one key in each object of the array. This solution will work for any valye for your key.
Working Fiddle
const badArray = [
{
college: {
id: 1, location: "Victoria", rating: 10,
alumni: [
{ alumni_id: 1, alumni_position: 1 },
{ alumni_id: 2, alumni_position: 3 },
],
},
},
{
college: {
id: 2, location: "New York", rating: 9,
alumni: [
{ alumni_id: 5, alumni_position: 7 },
],
},
},
];
const goodArray = badArray.map(item => Object.values(item)[0]);
console.log(goodArray);
If your key is constant as "college" you can perform this as.
const goodArray = badArray.map(item => item.college);
I have two JSON arrays with same fields as follows:
var total_90 = [
{ "date": "2011-11-14T17:22:59Z", "quantity": 2, "total": 90, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T17:07:21Z", "quantity": 2, "total": 90, "tip": 1, "type": "tab" },
{ "date": "2012-11-14T16:30:43Z", "quantity": 3, "total": 90, "tip": 0, "type": "tab" }
];
var tip_0 = [
{ "date": "2011-11-14T17:22:59Z", "quantity": 2, "total": 80, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T17:07:21Z", "quantity": 2, "total": 70, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T16:58:03Z", "quantity": 2, "total": 90, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T16:30:43Z", "quantity": 2, "total": 90, "tip": 0, "type": "tab" }
];
I need a third JSON file which has the intersection of the above two JSON files. (By intersection, I mean all the rows from both the JSON files which have TOTAL=90 AND TIP=0)
Is there some way to do this?
My expected output will be a third JSON file with the following output
{"date":"2012-11-14T16:30:43Z","quantity":3,"total":90,"tip":0,"type":"tab"},
{"date":"2011-11-14T16:58:03Z","quantity":2,"total":90,"tip":0,"type":"tab"},
{"date":"2011-11-14T16:30:43Z","quantity":2,"total":90,"tip":0,"type":"tab"}
You need to loop the 2 objects and merge the contents into 1 object.
For examples check this thread since this is a duplicate How can I merge properties of two JavaScript objects dynamically?
You could do the following to collect all the rows from both the JSON files which have TOTAL = 90 and TIP = 0 -
var total_90 = [
{ "date": "2011-11-14T17:22:59Z", "quantity": 2, "total": 90, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T17:07:21Z", "quantity": 2, "total": 90, "tip": 1, "type": "tab" },
{ "date": "2012-11-14T16:30:43Z", "quantity": 3, "total": 90, "tip": 0, "type": "tab" }
];
var tip_0 = [
{ "date": "2011-11-14T17:22:59Z", "quantity": 2, "total": 80, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T17:07:21Z", "quantity": 2, "total": 70, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T16:58:03Z", "quantity": 2, "total": 90, "tip": 0, "type": "tab" },
{ "date": "2011-11-14T16:30:43Z", "quantity": 2, "total": 90, "tip": 0, "type": "tab" }
];
// An empty arrays to contain final intersection array
var result = [];
/* now looping over both arrays to traverse all the elements from them */
// iterating over first array
total_90.forEach(x => {
// iterating over second array
tip_0.forEach(y => {
// push into output array only if total is 90 & tip is 0
if ((x.total == 90 && y.total == 90) && (x.tip == 0 && y.tip == 0)) {
result.push({
date: x.date,
quantity: x.quantity,
total: x.total,
tip: x.tip,
type: x.type
});
}
});
});
console.log(result);
Note - this can be optimized to reduce the time complexity.
function intersection(a, b)
{
var result = [];
for (var i = 0; i < a.length; i++){
if (a[i].total == 90 && a[i].tip == 0)
{
result.push(a[i]);
}
}
for (var i = 0; i < b.length; i++){
if (b[i].total == 90 && b[i].tip == 0)
{
result.push(b[i]);
}
}
return result;
}
JSFiddle
EDIT: Update the function with the use of concat to provide a slightly more short hand.
function intersection(a, b)
{
var result = [];
var c = a.concat(b);
for (var i = 0; i < c.length; i++){
if (c[i].total == 90 && c[i].tip == 0)
{
result.push(c[i]);
}
}
return result;
}
New JSFiddle
var total_90 = [
{"date":"2011-11-14T17:22:59Z","quantity":2,"total":90,"tip":0,"type":"tab"},
{"date":"2011-11-14T17:07:21Z","quantity":2,"total":90,"tip":1,"type":"tab"},
{"date":"2012-11-14T16:30:43Z","quantity":3,"total":90,"tip":0,"type":"tab"}
]
var tip_0 = [
{"date":"2011-11-14T17:22:59Z","quantity":2,"total":80,"tip":0,"type":"tab"},
{"date":"2011-11-14T17:07:21Z","quantity":2,"total":70,"tip":0,"type":"tab"},
{"date":"2011-11-14T16:58:03Z","quantity":2,"total":90,"tip":0,"type":"tab"},
{"date":"2011-11-14T16:30:43Z","quantity":2,"total":90,"tip":0,"type":"tab"}
]
allData['total_90'] = total_90;
allData['tip_0'] = tip_0;
use allData