簡體   English   中英

將數組中的相同元素組合為數組中的一個字符串的更簡潔的方法?

[英]More condense way to combine same elements in array to one string in array?

我正在嘗試學習如何重構我的代碼,並且我編寫了以下 function 塊:

joinSame = (arr) =>{
    let simplifiedArr = [];
    for(let i=0; i < arr.length; i++){
        const tempLast = arr.lastIndexOf(arr[i]);
        const element = arr[i].toString()
        if(i === tempLast){
            simplifiedArr.push(element);
        } else {
            const tempMultiplier = tempLast-i+1;
            simplifiedArr.push(element.repeat(tempMultiplier));
            i = tempLast;
        }
    }
    return simplifiedArr;
}

這個想法是,如果我輸入一個排序數組( [3,3,3,4,'a','a'] ),我希望 output 是一個將相似實體組合成字符串的數組( ['333', '4', 'aa'] )。 我嘗試使用 .map 和 .forEach 數組方法,但我的問題是試圖將 go 的索引“跳躍”到下一個唯一元素。

我是否通過嘗試將其重構為 a.map 或 .forEach 方法使事情變得過於復雜,還是我的代碼“好”足以讓它 go?

您可以使用reduce ,然后使用Object.values

 const arr = [3,3,3,4,'a','a']; const result = Object.values(arr.reduce((a,b)=>(a[b]=(a[b] || '')+b,a),{})) console.log(result);

暫無
暫無

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

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