2016-01-22 74 views
0

我需要你的帮助。在阵列中查找匹配的字符串并重新写入阵列

我希望能够在数组中找到一个字符串,并基于是否已经找到该值,以便能够相应地获取数组。

var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"] 

现在一些加工....

If ("BNI to" matches what is in the array temp then) { 

    Find the instance of "BNI to" and re-label to single name: Briefing Notes (Info) 
} 

If ("BNA to" matches what is in the array temp then) { 

    Find the instance of "BNA to" and re-label to single name: Briefing Notes (Approval) 

} 

重新写入和输出相同的温度阵列现在读作:

var temp = ["Briefing Notes (Info)", "Briefing Notes (Approval)", "Media Call", "Report Paper", "Issue Paper"] 
+0

而问题/问题是什么? – Andreas

+0

完全匹配或丢失一个? – MaxZoom

+0

问题是这对我来说似乎是微积分。我不知道如何编码。 – BobbyJones

回答

1

做一个map - 取代你需要什么 - 然后运行reduce以摆脱重复项:

var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"]; 

var formatted = temp.map(function(str) { 
    //Replace strings 
    if (str.indexOf("BNI to") > -1) { 
     return "Briefing Notes (Info)" 
    } else if (str.indexOf("BNA to") > -1) { 
     return "Briefing Notes (Approval)"; 
    } else { 
     return str; 
    } 
}).reduce(function(p, c, i, a) { 
    //Filter duplicates 
    if (p.indexOf(c) === -1) { 
     p.push(c); 
    } 
    return p; 
}, []); 

//Output: ["Briefing Notes (Info)", "Briefing Notes (Approval)", "Media Call", "Report Paper", "Issue Paper"] 
0

一对夫妇的mapreplace应该做的伎俩

var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"]; 
var result = temp.map(function(str) {return str.replace(/BNI/i, 'Briefing Notes (Info)');}).map(function(str) {return str.replace(/BNA/i, 'Briefing Notes (Approval)');}); 
console.log(result); 
0
var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"]; 
temp.forEach(function(v, i) { 
    temp[i] = v.replace(/^BNI to/, 'Briefing Notes (Info)') 
      .replace(/^BNA to/, 'Briefing Notes (Approval)'); 
}) 
0
$(document).ready(function() { 
     var temp = ["BNI to John", "BNI to Smith", "BNI to Jane", "BNA to Craig", "BNA to David", "BNA to Michelle", "Media Call", "Report Paper", "Issue Paper"]; 


     var BNIRegex = new RegExp("BNI to"); 
     var BNARegex = new RegExp("BNA to"); 

     var BNISubstituteString = "Briefing Notes (Info)"; 
     var BNASubstituteString = "Briefing Notes (Approval)"; 

     for (i = 0; i < temp.length; i++) { 
      temp[i] = temp[i].replace(BNIRegex, BNISubstituteString); 
      temp[i] = temp[i].replace(BNARegex, BNASubstituteString); 
      alert(temp[i]); 
     } 

    }); 
+0

警报仅用于验证目的,测试后请将其除去;) – aemorales1