'how to find elements in array with reference of another array

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



Solution 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));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben