首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在数组中找到匹配的字符串并重写数组。

在数组中找到匹配的字符串并重写数组。
EN

Stack Overflow用户
提问于 2016-01-22 20:15:39
回答 4查看 34关注 0票数 0

我需要你的帮助。

我希望能够在数组中找到一个字符串,并根据是否找到了该值,从而能够相应地移动该数组。

代码语言:javascript
复制
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"]

现在进行一些处理..。

代码语言:javascript
复制
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)

}

重写和输出相同的temp数组,现在读取如下:

代码语言:javascript
复制
var temp = ["Briefing Notes (Info)", "Briefing Notes (Approval)", "Media Call", "Report Paper", "Issue Paper"]
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-01-22 20:20:34

执行map --替换所需的内容--然后运行reduce以消除重复的内容:

代码语言:javascript
复制
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"]
票数 1
EN

Stack Overflow用户

发布于 2016-01-22 20:35:24

几个map和一个replace就可以了

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-01-22 20:37:45

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34955179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档