2016-01-22 70 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