【问题标题】:BASIC Javascript array function, issue is known but I cannot fathom a solutionBASIC Javascript 数组函数,问题是已知的,但我无法理解解决方案
【发布时间】:2018-07-05 12:53:38
【问题描述】:

在下面的函数中,我试图得到一个类似于这样的输出:

[[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591]。

我可以看到我嵌入的问题是我总是添加临时数组并推送到函数返回,因此,除了每个函数中的最后一个数字之外的所有单个数字都被也与数组对象一起推入目标数组。

我觉得我需要进一步的条件检查,但对于我的一生,我无法想出可行的解决方案。

任何建议将不胜感激。

const sortme = (unsortedArr)=> {

let tempArr = []; 

let outputArr = []; 

const reorderedArr = unsortedArr.sort((a,b) => a-b); 

reorderedArr.forEach((number, i) => {

    if ((i === 0) || (reorderedArr[i] === reorderedArr[i-1])) {
    tempArr.push(number);  
    }

    else {     
    outputArr.push(tempArr);
    tempArr = [];
    tempArr.push(number); 
}  
})

outputArr.push(tempArr[0]);
    return outputArr; 
}

const unsortedArr = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20]; 

sortme(unsortedArr); 

【问题讨论】:

    标签: javascript arrays higher-order-functions


    【解决方案1】:

    我会制作一个重复数据副本并 .map() 将其转换为包含原始(排序)数组中的值的数组,您使用 .forEach 获得:

    const unsortedArr = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];
    
    const sortMe = (arr) => {
      arr = arr.sort((a, b) => a - b);
      
      // a short way to dedupe an array
      // results in : 1, 2, 4, 5, 10, 20, 391, 392, 591
      let dedupe = [...new Set(arr)]; 
      let tmpArr;
    
      return dedupe.map(e => {
        tmpArr = []; // empty tmpArr on each iteration
        
        // for each element of the deduped array, look for matching elements in the original one and push them in the tmpArr
        arr.forEach(a => {
          if (a === e) 
            tmpArr.push(e);
        })
        
        if(tmpArr.length === 1)
          return tmpArr[0]; // in case you have [4] , just return the 4
        else
          return tmpArr; // in case you have [1,1,1,1]
        
        // shorthand for the if/else above
        // return tmpArr.length === 1 ? tmpArr[0] : tmpArr;
      });
    }
    
    const result = sortMe(unsortedArr);
    
    console.log(result);

    【讨论】:

    • 这看起来很酷,我正在努力理解它是如何运作的,但我会进一步研究它,地图是我想要使用的理想选择,但是你的解决方案让我的菜鸟眼睛非常困惑: D.谢谢!
    • @SimonDean 谢谢,我会在代码中添加 cmets
    • 这真的超级有用!我确实制定了自己的解决方案,但我可以看到我需要练习高阶函数,因为它们会使一切变得更短!
    【解决方案2】:

    这应该可以工作(使用reduce):

     
    const unsortedArr = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
    
    let lastValue = null;
    var newArr = unsortedArr.sort((a,b) => a-b).reduce((acc, value) => {
    
        if (acc.length == 0 || ((acc.length > 0 || !acc[acc.length-1].length) && lastValue !== value)) {
            acc.push(value);
        } else if (acc.length > 0 && lastValue === value) {
            acc[acc.length-1] = (acc[acc.length-1].length ? acc[acc.length-1].concat([value]): [value, value]);
        } 
        
        lastValue = value;
        return acc;
    }, []);
    
    
    console.log(newArr);

    【讨论】:

    • 4 ifs ,当我有超过2时,我通常使用switch/case
    • 哦,是的,我实际上会简化 reduce proc 中的逻辑。我会通过一些工作来减少它:)
    【解决方案3】:

    还有另一种方法,只是为了好玩:

    const unsortedArr = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
    
    var arr = unsortedArr.sort((a,b) => a-b).reduce((acc, value) => {
        if (acc.length > 0 && acc[acc.length-1].includes(value)) {
            acc[acc.length-1].push(value);
        } else {
            acc.push([value])
        }
        return acc;
    }, []).map((v) => v.length > 1 ? v: v[0]);
    
    console.log(arr);

    【讨论】:

      【解决方案4】:

      希望下面这个比较简单;

      function findSame(pos, sortedArr){
          for(let i =pos; i<sortedArr.length; i++){
              if(sortedArr[i] !== sortedArr[pos]){
                  return i
              }
          }
      }
      
      function clubSameNumbers(unsortedArr){
          let sortedArr = unsortedArr.sort((a,b)=>a-b) 
          //[ 1, 1, 1, 1, 2, 2, 2, 4, 5, 10, 20, 20, 391, 392, 591 ]
          let result = [] 
          for(let i = 0; i < sortedArr.length; i = end){
              let start = i
              var end = findSame(i, sortedArr)
              let arr = sortedArr.slice(i, end)
              arr.length > 1 ? result.push(arr) : result.push(...arr)         
          }
          return result
      }
      
      
      console.log(clubSameNumbers([1,2,4,591,392,391,2,5,10,2,1,1,1,20,20]))
      //[ [ 1, 1, 1, 1 ], [ 2, 2, 2 ], 4, 5, 10, [ 20, 20 ], 391, 392, 591 ]

      【讨论】:

        猜你喜欢
        • 2017-10-27
        • 1970-01-01
        • 1970-01-01
        • 2022-09-25
        • 1970-01-01
        • 2021-08-19
        • 2020-12-26
        • 2022-09-27
        • 1970-01-01
        相关资源
        最近更新 更多