簡體   English   中英

是否有 ES6 方法可以在數組中搜索包含另一個數組元素的元素?

[英]Is there an ES6 method to search an array for elements with elements from another array?

我有兩個包含一些參數值的數組。 數組中的所有元素都是如下所示的字符串:

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

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;
  }
}

嘗試這個。 這使用了 RegEx,並且不容易出錯。

您可以使用Mapmap

  • 首先從數組y創建一個 Map,按=分割每個元素,使用第一部分作為鍵,第二部分作為值
  • 遍歷x陣列,由分割的每個元素= ,並使用第一部分作為鍵來搜索Map ,如果它是從本使用價值Map否則返回而沒有任何改變

 let x = ["vorzugsreihe=J", "nennleistung=94,1127", "nenndrehzahl=31,9400"] let y = ["nenndrehzahl=500,3000"] let maper = new Map(y.map(v => { let [key, value] = v.split('=', 2) return [key, value] })) let final = x.map(v => { let [key, value] = v.split('=', 2) if (maper.has(key)) { return key + '=' + maper.get(key) } return v }) console.log(final)

嘗試這個:

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=94,1127", "nenndrehzahl=31,9400"], y = ["nenndrehzahl=500,3000"], result = y.forEach(word => { let [str, number] = word.split('='); x.forEach((wrd,i) => { if(wrd.split('=')[0].includes(str)) { x[i] = word; } }); }); console.log(x);

我建議使用 reduce + find 的組合 - 這會累積並為您提供您期望的結果。

 var x = [ "vorzugsreihe=J", "nennleistung=94,1127", "nenndrehzahl=31,9400"] var y = ["nenndrehzahl=500,3000"] var combinedArr = x.reduce((acc, elem, index) => { const elemFoundInY = y.find((yElem) => yElem.split("=")[0] === elem.split("=")[0]); if (elemFoundInY) { acc = [...acc, ...[elemFoundInY]] } else { acc = [...acc, ...[elem]]; } return acc; }, []) console.log(combinedArr);

您可以使用.startsWith()檢查元素是否以key=開頭,然后替換其值:

 let x = [ "vorzugsreihe=J", "nennleistung=94,1127", "nenndrehzahl=31,9400"]; let y = ["nenndrehzahl=500,3000"]; y.forEach(val => { let [key, value] = val.split("="); for (let i = 0; i < x.length; i++) { if (x[i].startsWith(`${key}=`)) x[i] = `${x[i].split("=")[0]}=${value}`; } }) console.log(x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM