Inheritance parent-group child-group in Vue.js - vue.js

How do I create a list of a parent-group (values will be passed from the database) with a child-group in it, which will have the same values as the parent-group.
For example a value called "assignment" which only allow objects.

// DB Set
// DB_table_field = value : [1, 2, 3 , 4, 5], parent_id : [2, 0, 4, 1, 1] // rand two field of id, and parent_id
// sample arr
var sampleArr = [1, 2, 3]
// find parent of parent array
var mergeArr = []
var arr = []
var oi = 2
var coi = oi
arr.push(oi)
while (oi > 0) {
var poi = sampleArr.find(status => status.value === parseInt(oi)).parent_id
if (poi === coi) {
oi = 0
} else {
oi = poi
if (oi > 0) {
arr.push(oi)
}
}
}
// find child of child array
var intialArrMyChild = []
var myId = 1
var myChild = sampleArr.filter(status => status.parent_id === parseInt(myId))
myChild.forEach(element => intialArrMyChild.push(element.value))
var rtnArr = []
var intialArr = []
var xChildArr = []
rtnArr = intialArrMyChild
intialArr = intialArrMyChild
while (rtnArr.length > 0) {
intialArr.forEach(service => {
xChildArr = []
var loopFindChild = sampleArr.filter(status => status.parent_id === parseInt(service))
loopFindChild.forEach(element => xChildArr.push(element.value))
loopFindChild.forEach(element => intialArr.push(element.value))
})
rtnArr = xChildArr
}
var childArr = intialArr.filter(function (item, pos) {
return intialArr.indexOf(item) === pos
})
mergeArr = arr.concat(childArr)
var arrc = mergeArr
var filteredArray = arrc.filter(function (item, pos) {
return arrc.indexOf(item) === pos
})
console.log(filteredArray, 'parentChildfilteredArray')

Related

Expand Text of Compact Data

I am stuck with some data manipulation.
This is a small portion of the input data (df):
site=c("C000-C002","C420-C421,C424")
histology=c("9835-9836","9811-9812,9837")
category=c("Leukemia","Leukemia")
df=data.frame(site,histology,category)
And this is what I want the processed data to look like:
You may assume Site and Histology are both 4-digit after text splitting.
In case anyone is interested, the full data table is here
Please help with the text processing, or if anyone knows an existing processed package or database in a similar format as the image, that would be great too.
Thank you very much.
I don't know R language. So I tried with Javascript as following.
function mapStartEnd(start, end) {
let list = [];
let info = {};
const siteStart = start.match(/([A-Z])(\d{3})/);
if (siteStart) {
const siteEnd = end.match(/([A-Z])(\d{3})/);
info = {
type: "site",
prefix: siteStart[1],
numLength: 3,
from: parseInt(siteStart[2], 10),
to: parseInt(siteEnd[2], 10),
};
}
const histologyStart = start.match(/\d{4}/);
if (histologyStart) {
const histologyEnd = end.match(/\d{4}/);
info = {
type: "histology",
prefix: "",
numLength: 4,
from: parseInt(histologyStart[0], 10),
to: parseInt(histologyEnd[0], 10),
};
}
const categoryStart = start.match(/[A-Z][a-z]+/);
if (categoryStart) {
const categoryEnd = end.match(/[A-Z][a-z]+/);
info = {
type: "category",
prefix: "",
numLength: 0,
from: categoryStart[0],
to: categoryEnd[0],
};
}
if (!info.numLength) {
list = [info.from, info.to];
} else {
for (let i = info.from; i <= info.to; i++) {
list.push(info.prefix + i.toString().padStart(info.numLength, "0"));
}
}
return list;
}
function c(list) {
return list.map((list2) => {
return list2.split(",").reduce((prev, cur) => {
const [start, end] = cur.split("-");
if (!end) prev.push(start);
else prev = [...prev, ...mapStartEnd(start, end)];
return prev;
}, []);
});
}
function map3(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
for (let j = 0; j < histologys.length; j++) {
const histology = histologys[j];
for (let k = 0; k < categorys.length; k++) {
const category = categorys[k];
// JSON format
// list.push({ site, histology, category });
// CSV format
list.push(`${site},${histology},${category}`);
}
}
}
return list;
}
function frame(sites, histologys, categorys) {
let list = [];
for (let i = 0; i < sites.length; i++) {
const site = sites[i];
const histology = histologys[i];
const category = categorys[i];
list = [...list, ...map3(site, histology, category)];
}
return list;
}
const site = c(["C000-C002", "C420-C421,C424"]);
const histology = c(["9835-9836", "9811-9812,9837"]);
const category = c(["Leukemia", "Leukemia"]);
const df = frame(site, histology, category);
console.log(df);
Result:
[
"C000,9835,Leukemia",
"C000,9836,Leukemia",
"C001,9835,Leukemia",
"C001,9836,Leukemia",
"C002,9835,Leukemia",
"C002,9836,Leukemia",
"C420,9811,Leukemia",
"C420,9812,Leukemia",
"C420,9837,Leukemia",
"C421,9811,Leukemia",
"C421,9812,Leukemia",
"C421,9837,Leukemia",
"C424,9811,Leukemia",
"C424,9812,Leukemia",
"C424,9837,Leukemia"
]
https://jsfiddle.net/dnu2g0vr/

What is the fastest way to create a union of many polygons in turfjs?

I have something like this but with large sets it's awfully slow:
let unionize = (triangles) => {
if(triangles.length == 0) {
return null
}
let ret = triangles[0].feature
triangles.forEach((t, index) => {
if(index > 0) {
ret = turf.union(t, t)
}
})
return ret
}
featureEach tends to be faster than a trivial array forEach although with more features the gain decreases.
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#5.1.6/turf.min.js"></script>
<script>
const generateGrid = (cellSide = 100, units = "kilometers") => {
const bbox = [-95, 30, -85, 40];
return turf.triangleGrid(bbox, cellSide, {
units
});
}
const unionizeForEach = (triangles) => {
console.time('unionizeForEach');
if (triangles.length == 0) {
return null
}
let ret = triangles[0];
triangles.forEach((t, index) => {
if (index > 0) {
ret = turf.union(ret, t)
}
});
console.timeEnd('unionizeForEach');
return ret
}
const unionizeFeatureEach = (triangles) => {
console.time('unionizeFeatureEach');
if (triangles.features.length === 0) {
return null
}
let ret = triangles.features[0];
turf.featureEach(triangles, function (currentFeature, featureIndex) {
if (featureIndex > 0) {
ret = turf.union(ret, currentFeature)
}
});
console.timeEnd('unionizeFeatureEach');
return ret;
}
[100, 50, 10].map(cellSide => {
const triangleGrid = generateGrid(cellSide, 'kilometers');
console.info(`triangleGrid has ${triangleGrid.features.length} features`);
const union_foreach = unionizeForEach(triangleGrid.features);
const union_featureeach = unionizeFeatureEach(triangleGrid);
console.assert(JSON.stringify(union_foreach) === JSON.stringify(union_featureeach));
console.log('\n---\n');
})
</script>

custom sum elements by key using lodash

I do have two objects containing keys like
var a = {bar:[1,2], foo:[7,9]}
var b = {bar:[2,2], foo:[3,1]}
I want to get the fallowing results:
var c = {bar:[3,4], foo:[10,10]}
I already have a for logic like:
for (let key in b) {
if (a[key]) {
a[key][0] += b[key][0];
a[key][1] += b[key][1];
}
else a[key] = b[key];
}
But I would like to make this logic in a lodash way. How can I Do it?
You can use create a function that takes n objects, and collects them to an array using rest parameters. Now you can spread the array into _.mergeWith() to combine the objects, and in the customizer function sum the items in the arrays using Array.map() or lodash's _.map() and _.add():
const { mergeWith, isArray, map, add } = _
const fn = (...rest) => _.mergeWith({}, ...rest, (o = [], s) =>
map(s, (n, i) => add(n, o[i]))
)
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You can also use lodash/fp to create a function that merges all values to a multidimensional array with _.mergeAllWith(), then transpose the arrays using _.zipAll(), and sums each array:
const { rest, flow, mergeAllWith, isArray, head, mapValues, zipAll, map, sum } = _
const fn = rest(flow(
mergeAllWith((o, s) => [...isArray(head(o)) ? o : [o], s]), // combine to a multidimensional array
mapValues(flow(
zipAll,
map(sum)
)),
))
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
You can accomplish this using plain JavaScript with Object.entries, concat and reduce:
const a = { bar: [1,2], foo: [7,9] };
const b = { bar: [2,2], foo: [3,1] };
const entries = Object.entries(a).concat(Object.entries(b));
const result = entries.reduce((accum, [key, val]) => {
accum[key] = accum[key] ? accum[key].map((x, i) => x + val[i]) : val;
return accum;
}, { });
console.log(result);

Table, computed property and vuex data

I'm in need of help with computed properties .. it's hard to explain but I'll try ..
I have a table with filter and pagination that I created.
When I pass the data directly from a request the API works,
but when I have to work with data coming from vuex I'm having trouble ...
Because I do not know when the data will be filled in vuex
And then I use the computed property because the moment the vuex is filled it will capture the data ..
However as the function that fills the data is the same one that is executed when I click on the page I crash the process and the page stops working.
Below is the computed property:
list(){
if (this.url_get == '' && this.$store.state.table.list.length > 0){
this.total_data = this.$store.state.table.list.length
this.repos = this.$store.state.table.list
this.getPaginatedItems(1)
}
var filter = this.configs.filter.toString().toLowerCase()
var items = ''
if (filter == ''){
items = this.dados
}else{
items = this.repos
}
const list = this.$lodash.orderBy(items, this.configs.orderBy, this.configs.order)
this.reverse = 1;
if (this.$lodash.isEmpty(filter)) {
return list;
}
var result = this.$lodash.filter(list, repo => {
return repo[this.filter_term].toString().toLowerCase().indexOf(filter) >= 0
})
return result
},
And the function:
getPaginatedItems(data) {
var items = this.repos
var page = data
var per_page = 10
var offset = (page - 1) * per_page
var max_item = offset+per_page
var paginatedItems = this.$lodash.slice(items, offset, max_item)
var obj = {
offset: offset,
current_page: page,
per_page: per_page,
total: items.length,
total_pages: Math.ceil(items.length / per_page),
data: paginatedItems,
last: offset+paginatedItems.length,
max_item: max_item
}
this.pagination = obj
this.dados = this.pagination.data
},
Request who fill the data in vuex
axios
.get(`api/getusuariosgrupo/${id}`)
.then(res => {
if (res.data.dados !== undefined && res.data.dados.length !== 0){
vmThis.isEditing = true
var d = {
list: res.data.dados,
length: res.data.dados.length
}
this.$store.commit('SET_TABLE', d)
}else{
vmThis.isEditing = false
}
vmThis.$bus.$emit('processando',{val: false})
})

How to create list of anonymous types in select clause?

Here is one of queries I am using in my project:
var carQuery = from cars in context.Cars
.Where(c => c.CarID==3)
from stockTypes in context.StockTypes
.Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty()
from carUnit in context.Car_Units
.Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty()
from carAttributes in context.Car_Attributes
.Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty()
from attribute in context.Attributes
.Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty()
select new
{
CarID = cars.CarID,
CarName = cars.CarName,
CarDescription = cars.CarDescription,
StockType = (stockTypes == null) ? null : new
{
StockTypeID = stockTypes.StockTypeID,
StockName = stockTypes.StockName
},
IsActive = cars.IsActive,
IsCab = cars.IsCab,
Unit = (carUnit == null) ? null : new
{
Id = carUnit.UnitId,
Name = carUnit.Unit.UnitName
},
Attributes = attribute
};
If the context.Attributes returns multiple rows, the whole resultset also returning multiple rows.
Is there any possibility to return a single car type with multiple attributes as a list of attributes to the car??
Please help.
Thanks,
Mahesh
You just need to move the attribute query inside the result set:
var carQuery = from cars in context.Cars
.Where(c => c.CarID==3)
from stockTypes in context.StockTypes
.Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty()
from carUnit in context.Car_Units
.Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty()
from carAttributes in context.Car_Attributes
.Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty()
select new
{
CarID = cars.CarID,
CarName = cars.CarName,
CarDescription = cars.CarDescription,
StockType = (stockTypes == null) ? null : new
{
StockTypeID = stockTypes.StockTypeID,
StockName = stockTypes.StockName
},
IsActive = cars.IsActive,
IsCab = cars.IsCab,
Unit = (carUnit == null) ? null : new
{
Id = carUnit.UnitId,
Name = carUnit.Unit.UnitName
},
Attributes =
from attribute in context.Attributes
.Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty()
.GroupBy(at => at.AttributeId)
select attribute
};