簡體   English   中英

如何使用同一數組中的其他項目更改數組中的項目

[英]How to change items in an array using other items in the same array

我需要將數組A更改為類似於數組B,確保散列項成為任何數量的非散列項的前一個,直到下一個散列項為止

const A = [ '# test',
  'test',
  '# layouts',
  'main',
  'nav' ]

const B = ['test/test',
    'layouts/main',
    'layouts/nav' ]

您可以為此使用reduce ,累加器應該是一個包含兩個值的對象,第一個將是results數組,另一個將是reducereduce用於生成路徑的當前哈希字符串。 一旦reduce完成其工作,我們就可以將累加器的result屬性存儲到我們的結果變量B

const B = A.reduce((acc, str) => {                           // for each string in the array A
   if(str.indexOf("#") === 0) {                              // if the string is hashed one
      acc.currentHash = str.slice(2);                        // set the current hash to this string
   } else {                                                  // otherwise
      acc.result.push(acc.currentHash + "/" + str);          // use the current hash to generate the resulting string of the current string
   }
   return acc;
}, { result: [], currentHash: ""}).result;                   // once reduce finishes, use '.result' to access the result array of the accumulator

例:

 const A = [ '# test', 'test', '# layouts', 'main', 'nav' ]; const B = A.reduce((acc, str) => { if(str.indexOf("#") === 0) { acc.currentHash = str.slice(2); } else { acc.result.push(acc.currentHash + "/" + str); } return acc; }, { result: [], currentHash: ""}).result; console.log(B); 

我的首選方法是將數組映射到所需的格式,然后過濾掉無關的標記。

const needle = '# ';
let directoryName = '';
const b = a.map((elem) => {
    if (elem.startsWith(needle)) {
        directoryName = elem.substring(needle.length);
        return;
    }
    return directoryName + '/' + elem;
}).filter(Boolean);

請注意,我已經優化了代碼的可讀性。 它將在數組上循環兩次,這幾乎可以肯定,因為此處的操作非常快。 但是,如果您擁有龐大的陣列並且需要每一點性能,那么易卜拉欣的答案會更合適。

這是可以利用Array.prototype.reduceObject.keys

 function modify(a, delimiter) { const f = a.reduce((accum, el) => { var s = el.replace(/\\s/g, ''); if (s.charAt(0) === delimiter) { accum.pointer = s.substring(1); accum.data[accum.pointer] = []; } else { accum.data[accum.pointer].push(el); } return accum; }, { pointer: null, data: {} }); return Object.keys(f.data).map(k => { var s = `${delimiter}${k}` var values = f.data[k]; values.forEach(v => { s += `/${v}` }); return s; }); } const A = ['# test', 'test', '# layouts', 'main', 'nav' ] const B = modify(A, "#"); console.log(B); 

暫無
暫無

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

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