letfriends=[["A1","X1"],["A2","X2"],["A3","X3"],["A4","X4"]];letdistances=[["X1",100.0],["X2",200.0],["X3",250.0],["X4",300.0]];// transform the array into an object to make it easier to process later// solution from https://stackoverflow.com/q/26454655/3695983distances=distances.reduce(function(p,c){p[c[0]]=c[1];returnp;},{});functioncalculateDistance(friends,distances){lettotal=0;for(letx=0;x<friends.length;x++)if(friends[x].length===2)total+=(distances[friends[x][1]]*2);returntotal;}
It doesn't use a smart algorithm to calculate the distance: grandma will visit a friend and then go back home, and continue with the next friend. If she doesn't know the city where a friend lives, she'll stay at home and meet the next friend.
Another version using array methods (and kind of unreadable):
JavaScript
It doesn't use a smart algorithm to calculate the distance: grandma will visit a friend and then go back home, and continue with the next friend. If she doesn't know the city where a friend lives, she'll stay at home and meet the next friend.
Another version using array methods (and kind of unreadable):
Here is a demo on CodePen.