0

I want to found the ids connection with the help of name connection

this are my container elements

  const TotalNodes = [ 
                             {id : 1, name : "apple"},
                             {id : 2 , name : "banana"},
                             {id : 3 , name : "orange"},
                             {id : 4 , name : "lamon"},
                             {id : 5 , name : "suger"},
                             {id : 6 , name : "salt"}
                          ]

this is my reference array

const NodesConnection = [
                            {source : "suger" , target : "salt"},
                            {source : "apple" , target : "orange"}
                          ]

this is final output

 const NodesConnectionWithIds = [
                                   {source : 5 , target : 6},
                                   {source : 1 , target : 3}
                                 ]

any help is so appreciatable

1

1 Answer 1

1

Here is a function that does the trick:

/**
 * 
 * @param {{id: number, name: string}[]} nodes
 * @param {{source: string, target: string}[]} connections
 * @returns {{source: number, target: number}[]}
 */
function matchNodes(nodes, connections) {
  return connections.map((connection) => {
    const source = nodes.find((node) => node.name === connection.source);
    const target = nodes.find((node) => node.name === connection.target);
    return {
      source: source.id,
      target: target.id,
    };
  });
}

console.log(matchNodes(TotalNodes, NodesConnection));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.