How to separate each sub group in main group Array using javascript

前端 未结 4 1577
南旧
南旧 2021-01-16 21:44

I have an Array. It contains several subgroups. Example:

let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]

I want

相关标签:
4条回答
  • var arr = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
    var result = [],
        lastVal = -1;
    while(arr.length) {
      var currentIndex = arr.length - 1;
      var currentValue = arr[currentIndex];
      var c = Math.floor(currentValue/10);
      if (c !== lastVal) {
        lastVal = c;
        result.push([currentValue]);
      }else{
        result[result.length-1].push(currentValue);
      }
      arr.splice(currentIndex, 1);
    }
    result.forEach(function(arr){ arr.reverse(); });
    console.log(result);

    0 讨论(0)
  • 2021-01-16 21:57

    Here's a solution using Ramda.js

    const x = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
    
    const f = R.pipe(
      R.sortBy(R.identity), 
      R.groupWith(R.pipe(R.subtract, Math.abs, R.equals(1)))
    )
    
    console.log(f(x))
    <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

    0 讨论(0)
  • 2021-01-16 22:06

    Use the Array reduce function :

    let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
    
    let groups = mainArray.reduce ( 
      (grps, el, i, main) => ((el === main[i-1] + 1 ? grps[0].push (el)
                                                    : grps.unshift ([el])), grps), []);
    
    [sub3, sub2, sub1] = groups;
    
    console.log (sub1, sub2, sub3);

    0 讨论(0)
  • 2021-01-16 22:07

    This will create an Array of Subarays:

    const arr = [50,51,52,53,54, 511,512,513,514, 521,522,523,524,525,526,527];
    let newArr = [];
    let temp = [arr[0]];
    
    for (let index = 1; index < arr.length; index++) {
      if (arr[index] == arr[index - 1] + 1) {
        temp.push(arr[index]);
      } else {
        newArr.push(temp);
        temp = [];
      }
      
      if (index == arr.length - 1) {
        newArr.push(temp);
      }
    }
    
    console.log(newArr)

    0 讨论(0)
提交回复
热议问题