简体   繁体   English

将数组中的相同元素组合为数组中的一个字符串的更简洁的方法?

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

I'm trying to learn how to refactor my code, and I have written the following function block:我正在尝试学习如何重构我的代码,并且我编写了以下 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;
}

The idea is that if I input a sorted array ( [3,3,3,4,'a','a'] ), I want the output to be an array with similar entities combined into a string ( ['333', '4', 'aa'] ).这个想法是,如果我输入一个排序数组( [3,3,3,4,'a','a'] ),我希望 output 是一个将相似实体组合成字符串的数组( ['333', '4', 'aa'] )。 I tried to use the.map and.forEach array method, but my problem is trying to "hop" the index to go to the next unique element.我尝试使用 .map 和 .forEach 数组方法,但我的问题是试图将 go 的索引“跳跃”到下一个唯一元素。

Am I overcomplicating things by trying to get it to refactor to a.map or.forEach method, or is my code "good" enough to let it go?我是否通过尝试将其重构为 a.map 或 .forEach 方法使事情变得过于复杂,还是我的代码“好”足以让它 go?

You can make use of reduce and then take Object.values :您可以使用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