Get the existing intersections between multiple object arrays - arrays

I have a couple of arrays which have some same ids. What I want to achieve is get the intersections between the arrays in plain javascript, no libraries. If there is a match of Ids and arraypicklist values are not equal between 2 or more arrays I should get an array with the matching Ids.
Below is my example which I tried but this ends up with no ids where I expect at least 1 match. In this case Id:123 as in the first and second array there is a match. So I would expect
intersection = [{"Id":"123","arrayPicklist":"Categorie__c"},{"Id":"123","arrayPicklist":"Regio__c"}];
fiddle:https://jsfiddle.net/ozckc0tw/4/
var buckets = [[{"Id":"123","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"}],
[{"Id":"124","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"},{"Id":"125","arrayPicklist":"Regio__c"},{"Id":"123","arrayPicklist":
"Regio__c"},{"Id":"126","arrayPicklist":"Regio__c"}]]
function IntersectionByKey(key) {
var i,
j,
k,
ret = [],
item,
args = [].slice.call(arguments, 1);
args.sort(function(a, b) {return a.length - b.length});
i:for(i=0; i<args[0].length; i++) {
item = [Object.assign(args[0][i], {})];
j:for(j=1; j<args.length; j++) {
for(k=0; k<args[j].length; k++) {
if(key in args[0][i] && args[0][i][key] == args[j][k][key]){
item.push(Object.assign(args[j][k], {}));
continue j;
}
}
continue i;
}
ret.push(item);
}
return ret;
}
var key = 'Id';
var intersection = IntersectionByKey.apply(null, [key].concat(buckets));
console.log('intersection '+JSON.stringify(intersection))

Done,Sorry, but I did not looked out your code, I tried my logic with your requirements, You can use it.
my logic
var buckets = [
[{
"Id": "123",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}],
[{
"Id": "124",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "125",
"arrayPicklist": "Regio__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "126",
"arrayPicklist": "Regio__c"
}]
],
intersection = [{
"Id": "123",
"arrayPicklist": "Categorie__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}];
var resArray = [];
for (var j = 0; j < intersection.length; j++) {
for (var i = 0; i < buckets.length; i++) {
for (var k = 0; k < buckets[i].length; k++) {
if (buckets[i][k].Id == intersection[j].Id && buckets[i][k].arrayPicklist == intersection[j].arrayPicklist) {
resArray.push(buckets[i][k]);
}
}
}
}
console.log(resArray);

Related

I can't use filter when I have objects inside an array and find last id, angular

I need your opinion in this situation:
I get from API with this function:
getRS(
idProject: string
): Observable<ResponseModel<RSModel>> {
return this.http.get<ResponseModel<RSModel>>(
ApiUrlsConfig.getRS(
idProject
)
);
}
this response:
{
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3",
}
],
"result": null
}
I need to use filter in this response because I should be get the last state for each id. For example, I want to display state 2 in item with id: id1. For this I want to use filter. The problem is because I can't use filter on it, I don't understand why.
I tried to write this code:
#Input() set jobId(jobId: string) {
this.optionsService
.getRS(
this.idProject
)
.pipe()
.subscribe((res) => {
let resId = res.filter((aaa)=>{
if(aaa.id === jobId){
res.slice(-1)[0].id
}
}
)
});
}
Not function.
Please can you share with me any idea?
Thank you
Try this logic:
Loop backwards throw it.
Loop backwards over index to the start.
Splice duplicates.
let response = {
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3"
}
],
"result": null
}
let data = response.data;
for (let i = data.length - 1; i >= 0; i--) {
for (let j = i - 1; j >= 0; j--) {
if (data[i].id === data[j].id) {
data.splice(j, 1);
j++;
}
}
};
console.log(data);
try this:
if(aaa.id == jobId){
return res.slice(-1)[0].id
}

Convert Flat JSON string into hierarchical using Parent ID

I am implementing a Mat-Tree using Angular Material. I have a flat JSON string like:
"Entity": [
{
"ID": 1,
"NAME": "Reports",
"PARENTID": "0",
"ISACTIVE": "Y",
"CREATIONDATE": "2020-03-31T15:08:11",
"UPDATIONDATE": "2020-03-31T15:08:11",
"CREATEDBY": 596241,
"UPDATEDBY": 596241
},
{
"ID": 2,
"NAME": "TMS - Reports",
"PARENTID": 1,
"ISACTIVE": "Y",
"CREATIONDATE": "2020-03-31T15:08:38",
"UPDATIONDATE": "2020-03-31T15:08:38",
"CREATEDBY": 596241,
"UPDATEDBY": 596241
},
{
"ID": 3,
"NAME": "TMS - Beneficiary ",
"PARENTID": 2,
"ISACTIVE": "Y",
"CREATIONDATE": "2020-03-31T15:09:34",
"UPDATIONDATE": "2020-03-31T15:09:34",
"CREATEDBY": 596241,
"UPDATEDBY": 596241
}
]
And I need to convert it into Key-value pairs based on their Parent ID. Something like:
{
Reports:
{
'Type 1 Reports': ['Beneficiary Reports', 'Some Other Report'],
'Type 2 Reports': null //No Children,
},
Some Other Menu Items: {
'My Parent Node': null,
'Some Other Menu Node': ['Child 1', 'Child 2']
}
}
So far, I am able to use this code to convert it into a parent-child hierarchy, but It has pushed all children into Items array which I cannot iterate with Mat-Tree. I need to get rid of the Items and have something like a key-value pair as the one I mentioned above:
generateTreeData(menuResponse)
{
var map = {};
for(var i = 0; i < menuResponse.length; i++){
var obj = menuResponse[i];
var parent = '';
obj.items= [];
map[obj.ID] = obj;
if(obj.PARENTID == "0")
{
parent = '-';
}
else
{
parent = obj.PARENTID;
}
if(!map[parent]){
//Means Parent doesnt exist i.e. node Itself is parent node
map[parent] = {
items: []
};
}
map[parent].items.push(obj);
}
return map['-'].items;
}
Problem:
The code puts children nodes in Items array. I need to get rid of the Items array and place it in key-value pairs like the one I mentioned above. How do I just extract the "NAME" and Items out of this JSON array and make a Key-Value pair? Something like the one I mentioned above?
The expected output structure doesn't seem right. What if there is a child for 'Beneficiary Reports' node.
The output structure for the input provided in the question should be like:
{
"Reports":[
{
"TMS - Reports":[
{
"TMS - Beneficiary ":[]
}
]
}
]
}
Check the following fiddle: https://jsfiddle.net/abby_7700/apkgeo1d/3/
var data = [];//your response goes here
var result = {};
var root = data.find(x => x.PARENTID == 0);
result[root.NAME] = [];
findAndAddChildren(root.ID, result[root.NAME]);
console.log(JSON.stringify(result));
function findAndAddChildren(parentID, collection) {
var rootChildren = data.filter(x => x.PARENTID == parentID);
for(var i = 0; i < rootChildren.length; i++) {
var child = rootChildren[i];
var temp = {};
temp[child.NAME] = [];
collection.push(temp);
findAndAddChildren(child.ID, temp[child.NAME]);
}
}

Protractor test not executing

I have a protractor test. I want to provide some data for a test so i can generate tests automatically.
My function is as below. The problem is that i can console log something after the opening of describe. But this is'nt the case after the it function.
The code:
bigTestFunction = function(testElements) {
testElements = JSON.parse(testElements);
for (i = 0; i < testElements.length; i++) {
var title = testElements[i].title;
var shouldText = testElements[i].should
var url = testElements[i].url;
var actions = testElements[i].action;
describe(title, function() {
it(shouldText, function() {
goToUrl(url);
for (x = 0; x < actions.length; x++) {
var action = actions[x].action;
var value = actions[x].value;
var element = actions[x].element;
var notEmpty = actions[x].notEmpty;
var nested = actions[x].nested;
if (action === 'sendKeys') {
sendKey(element, value);
}
if (action === 'click') {
click(element, notEmpty);
if (nested) {
for (x = 0; x < nested.length; x++) {
if (nested[x]['action'] === 'sendKeys') {
sendKey(nested[x]['element'], nested[x]['value']);
}
if (nested[x]['action'] === 'click') {
click(nested[x]['element'], nested[x]['notEmpty']);
}
}
}
}
}
});
});
}
}
testElements = JSON.parse(testElements);
the json:
[
{
"id": 1,
"title": "Small test one",
"should": "should start training",
"url": "https://ledmagazine.nl/home",
"actions": [
{
"id": 1,
"test_id": 1,
"element": "/html/body/div[1]/div/div/header/div/div[2]/div[2]/div/div/div/div/nav/section/ul/li[3]/a",
"action": "click",
"status": "notEmpty",
"value": "/html/body/div[1]/div/div/div[2]/div/div/div[1]/div/section",
"nested": {
"id": 1,
"action_id": 1,
"action": "sendKeys",
"element": "//*[#id=\"mce-EMAIL\"]",
"value": "dennisageffen#hotmail.com",
"created_at": null,
"updated_at": null
}
}
]
}
]
I think i'm really close but the function stops after 'describe(title, function() {...'
Propably you are missing beforeEach(function() {...} to get data.

Angularjs Splice in Nested Array

Hi can somebody help Removing element from nested json array like this
JSON
[{
"id": 1,
"name": "Furniture & Fixture",
"choice": {
"0": {
"req_goods": "table",
"qty": "10"
},
"1": {
"req_goods": "chair",
"qty": "5"
}
}
}, {
"id": 2,
"name": "Miscellaneous Property",
"choice": {
"0": {
"req_goods": "Office Rent",
"qty": "1"
}
}
}]
here how do I remove choice 1 of id 1 .
HTML
<div ng-repeat="cb in capital_budgets">
<div ng-repeat="choice in choices[$index]">
<input ng-model="cb.choice[$index].req_goods">
<input ng-model="cb.choice[$index].qty">
<button ng-hide="$first" ng-click="removeChoice($parent.$index,$index)">-</button>
</div>
<button ng-click="addNewChoice($index)">+</button>
</div>
JS
$scope.capital_budgets = [{"id":1,"name":"Furniture & Fixture"},
{"id":2,"name":"Miscellaneous Property"}];
$scope.choices = [{}];
$scope.choices[0] = [{}];
$scope.choices[1] = [{}];
$scope.choices[2] = [{}];
$scope.choices[3] = [{}];
$scope.choices[4] = [{}];
$scope.addNewChoice = function(id) {
$scope.choices[id].push({});
};
$scope.removeChoice = function(parent_id, id) {
$scope.choices[parent_id].splice(id, 1);
};
The Above removeChoice() remove last element but I want to remove the element that user choose to remove. please help i have been trying from 2 days.
You can make 'choice' of the array type as follows and use the index of the particular choice in the ng-repeat directive to remove the choice from the choices array.
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
vm.removeChoice = removeChoice;
vm.addChoice = addChoice;
function removeChoice(itemId, index) {
for (var i = 0; i < vm.items.length; i++) {
if (vm.items[i].id === itemId) {
vm.items[i].choices.splice(index, 1);
break;
}
}
}
function addChoice(index) {
var id = vm.items[index].choices.length + 1;
vm.items[index].choices.push({
id: id,
req_goods: "",
qty: 0
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<div ng-repeat="item in ctrl.items">
<h3>{{item.name}}</h3>
<div ng-repeat="choice in item.choices">
<input type="text" ng-model="choice.req_goods" />
<input type="text" ng-model="choice.qty" />
<button type="button" ng-click="ctrl.removeChoice(item.id, $index)">Remove</button>
</div>
<button type="button" ng-click="ctrl.addChoice($index)">Add</button>
</div>
</div>
</div>
You can remove choice "1" of id 1 using the below code snippet.
var json = [
{
"id": 1,
"name": "Furniture & Fixture",
"choice": {
"0": {
"req_goods": "table",
"qty": "10"
},
"1": {
"req_goods": "chair",
"qty": "5"
}
}
}, {
"id": 2,
"name": "Miscellaneous Property",
"choice": {
"0": {
"req_goods": "Office Rent",
"qty": "1"
}
}
}];
function removeChoice(json, parentId, choice) {
for (var i = 0; i < json.length; i++) {
if (json[i].id === parentId) {
delete json[i].choice[choice];
break;
}
}
}
removeChoice(json, 1, "1");
console.log(json);
If you want the the choice also to be of the same type as its parent element i.e. an array you could change your JSON as follows and do as shown in the below code snippet to remove a choice from the JSON
var json = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
function removeChoice(json, parentId, choiceId) {
for (var i = 0; i < json.length; i++) {
if (json[i].id === parentId) {
for (var j = 0; j < json[i].choices.length; j++) {
if (json[i].choices[j].id === choiceId) {
json[i].choices.splice(j, 1);
break;
}
}
break;
}
}
}
removeChoice(json, 1, 1);
console.log(json);
In both of the above methods I've passed the source you want to modify as a parameter to the removeChoice function whereas you can also directly use a variable available within the scope of execution of the removeChoice function and pass only parentId and choiceId as parameters in the below code snippet, you can replace items with the object on your controller's $scope.If you prefer isolation of the code you can pass the items object as a parameter to the removeChoice function as it won't be dependent on the external components directly being used in the method body, I would suggest to have separation of concerns.
var items = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
function removeChoice(parentId, choiceId) {
for (var i = 0; i < items.length; i++) {
if (items[i].id === parentId) {
for (var j = 0; j < items[i].choices.length; j++) {
if (items[i].choices[j].id === choiceId) {
items[i].choices.splice(j, 1);
break;
}
}
break;
}
}
}
removeChoice(1, 1);
console.log(items);
Try This
$scope.removeChoice = function(parent_id,id) {
var TempArr=[];
var parentLength=$scope.choices[parent_id].length;
for(i=0;i<parentLength;i++ ){
if(parentLength[i]!==id){
TempArr.push(parentLength[i]);
}
if(i==parentLength-1){
$scope.choices[parent_id]=[];
$scope.choices[parent_id]=TempArr;
}
}
};

How remove the attribute from anguler.js array?

I am having an anguler.js array like below,
"serviceLevels": [
{
"cutOffTime": "11:00",
"dgs": [
{
"active": "Y",
"cutoffTime": null,
"dgId": "DG100",
"locations": [
{
"active": "Y",
"effEndDt": "2015-05-15T19:37:00+0000",
"effStDt": "2015-05-15T19:37:00+0000",
"locId": "BBY_1000",
"rank": 1
}
],
"rank": "1"
},
{
"active": "Y",
"cutoffTime": null,
"dgId": "DG8113",
"locations": [
{
"active": "Y",
"effEndDt": "2015-08-11T09:46:00+0000",
"effStDt": "2015-08-11T09:46:00+0000",
"locId": "BBY_1064",
"rank": 1
}
],
"rank": "1"
}
],
"overrideCutOffTime": "",
"serviceLevel": "SAME_DAY"
}
]
From the above array I need to remove cutoffTime attribute from dgs array.I'm trying like this but its taking null value, can anyone help me on this?.
var svcs = eval($scope.rgnSvcLevels);
for (var j = 0; j < svcs.length; j++) {
var dgs = eval(svcs[j].dgs)
if (dgs != null) {
for (var k = 0; k < dgs.length; k++) {
dgs[k].cutoffTime=null
}
}
}
try this
delete dgs[k].cutoffTime;
For any Javascript basic operation always search first MDN. Here is official documentation for delete property from object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
/*detele object property */
var svcs = eval($scope.rgnSvcLevels);
for (var j = 0; j < svcs.length; j++) {
var dgs = eval(svcs[j].dgs)
if (dgs != null) {
for (var k = 0; k < dgs.length; k++) {
delete dgs[k].cutoffTime;
}
}
}

Resources