Javascript 是否有ES6方法来搜索一个数组中包含其他数组元素的元素?

Javascript 是否有ES6方法来搜索一个数组中包含其他数组元素的元素?,javascript,arrays,Javascript,Arrays,我有两个数组,其中包含一些参数值。数组中的所有元素都是字符串,如下所示: x = [ "vorzugsreihe=J", "nennleistung=94,1127", "nenndrehzahl=31,9400"] y = ["nenndrehzahl=500,3000"] 预期产出将是: x = [ "vorzugsreihe=J", "nennleistung=94,1127", "nenndrehzahl=500,3000"] 我尝试过使用Array.Filter,但似乎无法仅对部分

我有两个数组,其中包含一些参数值。数组中的所有元素都是字符串,如下所示:

x = [ "vorzugsreihe=J", "nennleistung=94,1127", "nenndrehzahl=31,9400"]
y = ["nenndrehzahl=500,3000"]
预期产出将是:

x = [ "vorzugsreihe=J", "nennleistung=94,1127", "nenndrehzahl=500,3000"]
我尝试过使用
Array.Filter
,但似乎无法仅对部分内容进行筛选(比如从字符串开始,而不是从整个字符串开始,因为值不同,这将不匹配)


我希望能够遍历数组
Y
中的每个元素,搜索数组
X
中是否存在元素(“=”之前的字符串),并替换数组
X
中该元素的值。您可以使用
Map
Map

  • 首先从数组
    y
    创建一个映射,按
    =
    拆分每个元素,使用第一部分作为键,第二部分作为值
  • x
    数组上循环,将每个元素按
    =
    拆分,并使用第一部分作为键在
    Map
    中搜索,如果它是当前的,则使用
    Map
    中的值,否则返回而不做任何更改
设x=[“vorzugsreihe=J”,“nennleistung=941127”,“nenndrehzahl=319400”]
设y=[“nenndrehzahl=5003000”]
让maper=newmap(y.Map(v=>{
让[key,value]=v.split('=',2)
返回[键,值]
}))
让final=x.map(v=>{
让[key,value]=v.split('=',2)
if(映射器has(键)){
返回键+'='+maper.get(键)
}
返回v
})
console.log(最终版)
尝试以下操作:

y.forEach(item => {
  const str = item.split("=")[0];
  const index = x.findIndex(el => el.startsWith(str));
  if (index) {
    const split = x[index].split('=');
    x[index] = `${split[0]}=${split[1]}`;
  }
})

对于
y
数组中的每个值,迭代并检查
x
数组中是否存在该单词。找到匹配项后,只需更新值。(以下解决方案对原始阵列进行了变异)

const x=[“vorzugsreihe=J”,“nennleistung=941127”,“nenndrehzahl=319400”],
y=[“nenndrehzahl=5003000”],
结果=y.forEach(word=>{
让[str,number]=word.split('=');
x、 forEach((wrd,i)=>{
如果(wrd.split('=')[0]。包括(str)){
x[i]=单词;
}
});
});

控制台日志(x)我建议使用reduce+find的组合-这将累积并提供您期望的结果

var x=[“vorzugsreihe=J”,“nennleistung=941127”,“nenndrehzahl=319400”]
变量y=[“nenndrehzahl=5003000”]
var combinedArr=x.reduce((会计科目、要素、指数)=>{
常量elemFoundInY=y.find((yElem)=>yElem.split(“=”[0]”)==elem.split(“=”[0]);
if(elemFoundInY){
acc=[…acc,…[elemFoundInY]]
}否则{
acc=[…acc,…[elem]];
}
返回acc;
}, [])

console.log(combinedArr)
您可以使用
.startsWith()
检查元素是否以
键=
开头,然后替换其值:

设x=[“vorzugsreihe=J”,“nennleistung=941127”,“nenndrehzahl=319400”];
设y=[“nenndrehzahl=5003000”];
y、 forEach(val=>{
让[key,value]=val.split(“=”);
for(设i=0;iconsole.log(x)
用于(var i=0;i请提供预期的输出您可以分享您的
.filter
code吗?@Hassaniam我已经添加了预期的输出。这只是第二个数组只有一个元素的示例。但是它可能有多个元素。如果一个值等于您要查找的键,例如,
vorzugsreiche=nenndrehzahl现在,当
y=['abc=2']
x=['abcd=3']
for(var i=0;i<x.length;i++){
  var currentStr = x[i];
  var currentInterestedPart = /(.+)=(.+)/.exec(currentStr)[1];
  var replacePart = /(.+)=(.+)/.exec(currentStr)[2];
  for(var j=0;j<y.length;j++){
   if(!y[j].startsWith(currentInterestedPart)) {continue;}
   var innerReplacePart = /(.+)=(.+)/.exec(y[j])[2];
   x[i] = currentStr.replace(replacePart,innerReplacePart);break;
  }
}