javascript odd and even separation in an array of numbers

前端 未结 5 1617
一整个雨季
一整个雨季 2021-01-06 19:04

i wants to separate an array with two groups (odd and even) sequentially. but when i try this:

5条回答
  •  伪装坚强ぢ
    2021-01-06 19:47

    I believe this can be covered by lodash _.partition:

    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    var [odds, evens] = _.partition(arr, function(n) {
      return n % 2;
    });
    console.log(_.concat(odds, evens));

    Or even shorter:

    _.groupBy(arr, function(n) {return (n % 2) ? 'odd' : 'even';})
    

提交回复
热议问题