arr1 = [
{
nodeId: 1,
xvalue: 200,
yvalue: 300,
},
...
]
arr2 = [
{
parentNode: 1,
childNode:3,
},
...
]
arr1 are have node's id and node's xy coordinate data. and arr2 have link between node, parentNode to childNode.
i need to make new array for parentNode's xy coordinate and childNode's xy coordinate data like this
arr3 = [
{
sourceX: 200,
sourceY: 300,
targetX: 500,
targetY: 600,
}
]
how can I make array like this?
You would use a map function, and then lookup the joins.
const joined = arr2.map(it=>{
const parent = arr1.find(a=>a.nodeId === it.parentNode)
const child = arr1.find(a=>a.nodeId === it.childNode)
return {
sourceX: parent.xvalue,
sourceY: parent.yvalue,
targetX: child.xvalue,
targetY: child.yvalue,
}
}
The below may be one possible solution to achieve the desired objective:
Code Snippet
const getNewArr = (ar1, ar2) => (
ar2.map( // iterate over 'ar2'
({parentNode, childNode}) => { // de-structure iterator for parentNode, childNode
const {xvalue: sourceX, yvalue: sourceY} = ar1.find(
({nodeId}) => (nodeId === parentNode) // match 'ar1' nodeId with parent
) ?? {xvalue: 'notFound', yvalue: 'notFound'}; // if no match found
const {xvalue: targetX, yvalue: targetY} = ar1.find(
({nodeId}) => (nodeId === childNode) // match 'ar1' nodeId with child
) ?? {xvalue: 'notFound', yvalue: 'notFound'}; // no match found
return {sourceX, sourceY, targetX, targetY}
}
)
);
const arr1 = [
{
nodeId: 1,
xvalue: 200,
yvalue: 300,
},
{ // the childNode must have a matching 'id'
nodeId: 3,
xvalue: 500,
yvalue: 600,
},
];
const arr2 = [
{
parentNode: 1,
childNode: 3,
}
];
console.log(getNewArr(arr1, arr2));
Explanation
Inline comments in the above code-snippet describe each step. For any further clarifications, please use comments below.
EDIT
Using .map and .find along with de-structuring and implicit return.
ar2.map(
({parentNode, childNode}) => (
{xvalue: sourceX, yvalue: sourceY} = ar1.find(
({nodeId}) => (nodeId === parentNode)
) ?? {xvalue: 'notFound', yvalue: 'notFound'},
{xvalue: targetX, yvalue: targetY} = ar1.find(
({nodeId}) => (nodeId === childNode)
) ?? {xvalue: 'notFound', yvalue: 'notFound'},
{sourceX, sourceY, targetX, targetY}
)
)