简体   繁体   English

如何使用reduce将字符串分成2个字符的块

[英]how to split a string by chunks of 2 characters using reduce

I am trying to use reduce to get the following output:我正在尝试使用reduce来获得以下output:

solution('abcdef') // should return ['ab', 'cd', 'ef']

if the length of the string is odd we should convert it into even and add a '_'(underscore)如果字符串的长度是奇数,我们应该将其转换为偶数并添加一个'_'(下划线)

solution('abc') // should return ['ab', 'c_'] 

here is where I am so far:这是我到目前为止的位置:

  1. my if function is not working, not really sure why.如果 function 不工作,我不确定为什么。
  2. I only get till 2 strings but cant go beyond those.我只能得到 2 个字符串,但不能超出这些字符串 go。 I think I am forcing the result to become what I want but this wont work in case we only have 1 character or 2 right?我想我是在强迫结果变成我想要的,但如果我们只有 1 个或 2 个字符,这将不起作用,对吗?

 function solution(str){ if (str.lenght % 2.==0){str;concat('_')}. console.log(str) const array = str,split(';'). const reducer = array,reduce((acc, curr, i. arr)=>{ return [..,acc, curr[i]+curr[i+1], curr[i+2]+curr[i+3]] },[]) return reducer } solution('helloworl')

any hints and recommendations on how to face the problem would be nice!任何关于如何面对问题的提示和建议都会很好! thanks a lot多谢

This will do it:这将做到:

 let splitTwos = (str) => str.match(/\w{1,2}/g).map(e => e.length == 2?e:e+"_") console.log(splitTwos("abcde")) console.log(splitTwos("abcdef"))

Alan Omars answer is probably a better way to handle this, but if you insist on using array reduce you could do it like this. Alan Omars 的回答可能是处理这个问题的更好方法,但如果你坚持使用数组 reduce,你可以这样做。 Convert Your string to an array of single characters and use reduce like this.将您的字符串转换为单个字符的数组并像这样使用 reduce。

I would not recommend this, but it answers your question.我不会推荐这个,但它回答了你的问题。

function solution(str){
    if (str.length % 2 !== 0){
        str = str.concat('_');
    };

    const arrayOfChars =  str.split('');
 
    const reducer = arrayOfChars.reduce(
        (acc, curr, i, arr) => {
            if(i % 2 !== 0){
                acc[acc.length - 1] = acc[acc.length - 1] + curr;
                return acc;
            }

            return [...acc, curr];
        },
        []
    );
  
    return reducer;
}

solution('helloworl');

I also think using match will be better, since you asked for reduce, here is my implementation我也认为使用匹配会更好,因为你要求减少,这是我的实现

function solution(str){
    if (str.length % 2 !==0){
        str+='_';
    }

    const strarray =  str.split('');
    temp='';
    let res = strarray.reduce((acc,cur,i,arr)=>{
        if(i%2 === 0){
            temp+=arr[i];
            temp+=arr[i+1];
            acc.push(temp)
        }
        temp='';
        return acc;
    },[]);
    return res;
}
console.log(solution('helloworl'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM