如何用另一个数组中的元素替换数组中元素中的字符串?

时间:2017-01-31 15:01:50

标签: javascript arrays replace

嗨所以我的目标是将array1(2x2)中与arrayChoose(3x1)中的单词匹配的所有单词替换为arrayReplacewith(3x1)中使用Javascript的单词。我已经尝试了几种方法,包括映射和替换,但我会绕圈子而不知道如何继续。

编辑:只是添加一些上下文,我从csv文件加载所有数组。 同样选择和替换数组可能不一定是相同的长度...

edit2:面临的问题:我见过的所有例子都是关于向量而不是矩阵。其次,任何替换所有元素中的字符串的解决方案只会替换字符串的第一个实例,而我无法实现全局替换。

非常感谢任何帮助。感谢。

var array1 = [["today is the day","or maybe it's tomorrow"],["who knows really","it's just where we are"]];

var arrayChoose = ["today", "tomorrow", "just"];

var arrayReplacewith = ["monday", "tuesday", "not"];

解决方案 感谢所有贡献他们答案的人。我使用了@ mohamed-ibrahim提供的那个。请参阅下面的解决方案...(从csv文件加载的数组,有关完整示例,请参阅here

var arrayIncorrect = [ [ 'Trump has ordered', 'flight attendants to stop' ],
  [ 'shorter people to ', 'restrict tourism.' ],
  [ 'Now all they ', 'need is a wall.' ] ];

var dataChoose = [ [ 'Trump' ],
  [ 'stop' ],
  [ 'people' ],
  [ 'restrict' ],
  [ 'wall' ] ];

var dataReplace = [ [ 'Kim Jong-un' ],
  [ 'wear' ],
  [ 'skirts' ],
  [ 'boost' ],
  [ 'airplane' ] ];

arrayCorrect=
    arrayIncorrect.map(function(array1){
      return array1.map(function(ele){
               dataChoose.forEach(function(choose){
                 ele = ele.replace(new RegExp(choose, 'g'),  dataReplace[dataChoose.indexOf(choose)]) ;
               })
               return ele;
             })
    });

    console.log(arrayCorrect)

如果有任何问题,请与我们联系。

4 个答案:

答案 0 :(得分:1)

尝试以下方法:

var array1 = [["today is the day","or maybe it's tomorrow"],["who knows really","it's just where we are"]];
var arrayChoose = ["today", "tomorrow", "just"];
var arrayReplacewith = ["monday", "tuesday", "not"];

array1 = 
   array1.map(function(array2){
     return array2.map(function(ele){
              arrayChoose.forEach(function(choose){
                ele = ele.replace(new RegExp(choose, 'g'),  arrayReplacewith[arrayChoose.indexOf(choose)]) ;
              })
              return ele;
            })
   });

答案 1 :(得分:1)

两个简单的map将会解决这个问题,如果选择数组的条目多于替换数组,则可能会抛出错误,因此您需要确保不是这种情况。

var array1 = ["today is the day", "or maybe it's tomorrow", "who knows really", "it's just where we are"];
var arrayChoose = ["today", "tomorrow", "just"];
var arrayReplacewith = ["monday", "tuesday", "not"];

array1 = array1.map(v => {
  let s = v.split(" ").map(st => {
    let index = arrayChoose.indexOf(st);
    return index > -1 ? arrayReplacewith[index] : st;
  });
  return s.join(" ");
});

console.log(array1);

答案 2 :(得分:1)

使用.map.indexOf与ES6 arrow functions的一种方法:

replaceArr = (arrOriginal, arrWordsToMatch, arrWordsToReplace) => {        
    if (arrWordsToMatch.length != arrWordsToReplace.length) throw "arrWordsToMatch and arrWordsToReplace must have exact length"
    return arrOriginal.map( (phrase) => {
        return phrase.split(" ").map( (word) => {
            let foundIndex = arrWordsToMatch.indexOf(word)
            return (foundIndex > -1) ? arrWordsToReplace[foundIndex] : word
        }).join(" ")
    })
}

let newArray = replaceArr(array1, arrayChoose, arrayReplacewith);

console.log(newArray);
/*
  [ 'monday is the day',
  'or maybe it\'s tuesday',
  'who knows really',
  'it\'s not where we are' ]
*/

注意:由于arrWordsToMatcharrWordsToReplace必须具有相同的长度,如果尺寸不同,则会引发错误。

答案 3 :(得分:1)

您可以使用正则表达式和替换字符串的对象。



var array = [["today is the day", "or maybe it's tomorrow"], ["who knows really", "it's just where we are"]],
    object = { today: 'monday', tomorrow: 'tuesday', just: 'not' },
    result = array.map(function (a) {
        return a.map(function(b) {
            return b.replace(RegExp(Object.keys(object).join('|'), 'g'), function (s) {
                return object[s];
            });
        });
    });

console.log(result);




ES6



var array = [["today is the day", "or maybe it's tomorrow"], ["who knows really", "it's just where we are"]],
    object = { today: 'monday', tomorrow: 'tuesday', just: 'not' },
    result = array.map(a => a.map(b => b.replace(RegExp(Object.keys(object).join('|'), 'g'), s => object[s])));

console.log(result);