首页 > 解决方案 > 如果数组中的项目与另一个数组中的项目重合,则替换它们

问题描述

我有一个培训任务来检查阵列是否与另一个阵列匹配。找到的匹配项必须替换为任何值。

在一种情况下,我做到了,但使用for...of出现问题 - 我不明白为什么。

//source array
let arr = ['one', 'two', 'three', 'four', 'five', 'six'];

//array to compare
let arrForChange = ['one', 'four', 'six'];

从源数组更改一项很容易

let changedArr = arr.map(el => { if( el === 'four'){ 
  return el = 4;
  } else { 
  return el = el}  }         
);
// console.log(changedArr); // one,two,three,4,five,six

列表上的替换更有趣一些。我在这里使用.includes()

//This variant work 
let cahngedArrFromList = arr.map(el => {
  if(arrForChange.includes(el)){
    return 'A';
  } else {
    return el;
  }  
});
// console.log(cahngedArrFromList); // A,two,three,A,five,A

寻找不同的选择更有趣。在这里我使用for...of并且出现问题,结果不是我所期望的 - 只替换了第一个值。

//This variant do not work  =(
let cahngedArrFromListTwo = arr.map(el => { 
  for (const item of arrForChange){
    if (item === el){
      return 'A';
    } else {
      return el;
    }
  }
});
// console.log(cahngedArrFromListTwo); // A,two,three,four,five,six

如果您删除条件else,那么一切似乎都有效......但没有

let cahngedArrFromListThree = arr.map(el => { 
  for (const item of arrForChange){
    if (item === el){
      return 'A';
    } /* else {
      return el;
    } */
  }
});
// console.log(cahngedArrFromListTree); // A,,,A,,A

你能解释一下for...of行为吗?还是我使用不当?

标签: javascriptarraysloopsfor-loopreplace

解决方案


最简单的方法是将索引查找与替换映射结合起来。

如果数组中的当前项在过滤器列表中,则在替换映射中查找其值作为键并返回其值。如果映射中不存在该键,则返回原始值。

const replacements = {
  'one'   : 1,
  'two'   : 2,
  'three' : 3,
  'four'  : 4,
  'five'  : 5,
  'six'   : 6
};

let filter = [ 'one', 'four', 'six' ],
    input  = [ 'one', 'two', 'three', 'four', 'five', 'six' ];

console.log(replaceArrayItem(input, filter, replacements));

function replaceArrayItem(arr, filterArr, replMap) {
  return arr.map(item => filterArr.indexOf(item) > -1 ? replMap[item] || item : item);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }


推荐阅读