user7066345 user7066345 - 17 days ago 5
Javascript Question

what are the most efficient ways to return a value from a loop?

What are the most efficient ways to return a value from a loop? FlowId in the following example represents a concatenation of region names followed by "Flow". For example, "NortheastSoutheastFlow", "TexasSoutheastFlow", etc. regionNames represents an array of region names stored as a global variable like ['Northeast','Southeast','Texas']. The regionName function param represents a known region name and the goal of the function is return the other region name included in the flow:

function getOtherFlowRegionName(flowId, regionName)
{
regionNames.forEach(function(otherRegionName)
{
if(flowId.indexOf(otherRegionName) > -1)
return otherRegionName;
}
}


Solution can be in either jquery or vanilla js.

Answer

Here are 4 options that you can use to return a value from a loop like you have described.

Edit - After re-reading the quesiton, I realized you were looking for the parts of the flowId that did not match the region or "Flow". Is this what you're looking for?

Update - After re-re-reading your question, I am now under the understanding that you are wanting to pass in a regionName, rather than match the first one in the regionNames array. This should be the last edit!

function getOtherFlowRegionName(flowId, regionName) {
  var otherRegionName = "";
  flowId = flowId.replace(regionName, "").replace("Flow", "");
  // option 1 (iterates over all elements in regionNames)
  regionNames.forEach(function(region) {
    if (flowId.indexOf(region) > -1) {
      otherRegionName = region;
    }
  });
  // option 2 (stops when it reaches the first true value)
  regionNames.some(function(region) {
    if (flowId.indexOf(region) > -1) {
      otherRegionName = region;
      return true;
    }
  });
  // option 3 (iterates over all elements in regionNames)
  otherRegionName = regionNames.reduce(function(name, region) {
    return flowId.indexOf(region) > -1 ? region : name;
  }, "");
  // option 5 (stops when it reaches the first true value)
  for (var i = 0; i < regionNames.length; i++) {
    var region = regionNames[i];
    if (flowId.indexOf(region) > -1) {
      otherRegionName = region;
      break;
    }
  }
  return otherRegionName;
}
var flow1 = "NortheastSoutheastFlow";
var flow2 = "TexasSoutheastFlow";
var flow3 = "TexasNortheastFlow";
var regionNames = ['Northeast', 'Southeast', 'Texas'];

console.log(getOtherFlowRegionName(flow1, "Northeast"));
console.log(getOtherFlowRegionName(flow1, "Southeast"));
console.log(getOtherFlowRegionName(flow2, "Texas"));
console.log(getOtherFlowRegionName(flow2, "Southeast"));
console.log(getOtherFlowRegionName(flow3, "Texas"));
console.log(getOtherFlowRegionName(flow3, "Northeast"));