Javascript reduce-在多个变量中拆分累加器

时间:2018-08-26 14:29:49

标签: javascript reduce

为什么t在第二次迭代中变成undefined

function findShortest(s){
 const arr = s.split(' ');
  
 arr.reduce(([acc, t], curr, idx) => {
  console.log('t', t)

  if (curr.length < t.length) {
      // some code
      t = curr;
    } else { 
      // some code
    }
    return acc;
  }, [[], '']);
  
  return arr;
  
}

console.log(findShortest('how are you doing this wonderfull coding man'));

我尝试在一次迭代中从数组中筛选出最短的单词,所以我不需要循环数组来获取最短的单词,然后再次进行筛选。您可以看到我的第一次尝试。我最终得到了这个:

 const arr = s.split(' ');
  
 let shortest = 50;
  
 return arr.reduce((acc, curr) => {
  	if (curr.length < shortest) {
    	acc = [];
      acc.push(curr);
      shortest = curr.length;
    } else if (curr.length === shortest) {
       acc.push(curr);
    }
    return acc;
  }, []);

但是为什么第一种方法t不确定?

2 个答案:

答案 0 :(得分:1)

您可以将数组作为结果集,并对照第一个收集的字符串的长度进行检查。在开始时,检查蓄电池是否存在。

function findShortest(s) {
   return s
       .split(' ')
       .reduce((acc, curr) => {
           if (!acc || curr.length < acc[0].length) {
               return [curr];
           }
           if (curr.length === acc[0].length) {
               acc.push(curr);
           }
           return acc;
       }, undefined);
}

console.log(findShortest('how are you doing this wonderfull coding man'));

答案 1 :(得分:0)

简化为对象,其中键是长度,值是相同长度单词的数组。

function findShortest(s) {
  const wordsObj = s
    .split(' ')
    .reduce((acc, curr) => {
      const len = curr.trim().length;
      if (len) {       
        acc[len] = (acc[len] || []).concat(curr);      
      }
      return acc;
    }, {});

  return wordsObj[Math.min(...Object.keys(wordsObj))]
}

console.log(findShortest('how are you doing this wonderfull coding man'));