【问题标题】:How to make union of nested array in lodash如何在 lodash 中合并嵌套数组
【发布时间】:2016-11-18 18:54:55
【问题描述】:

我有以下数组格式,我想使用 lodash 或普通 js 来合并它。

var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]

我想将所有这些合并为一个,输出应低于数组。

testArray  = [1,2,3,4,5,6,7,8,9,10]

【问题讨论】:

标签: javascript lodash


【解决方案1】:

您可以将flattenDeep_.union 结合使用。如果需要,应用排序

var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]],
    result = _.chain(testArray)
             .flattenDeep()
             .union();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

【讨论】:

  • 我不知道为什么 OP 想要创建一个像 [1,2,3,4,5,6,7,8,9,10] 这样的数组。但是你的答案像 [1,2,3,4,5,6,7,8,10,9] 。为什么最后两个数字是交换的?是对还是错?
  • @prasad,unique 维护项目的顺序。如果需要,然后进行排序。
【解决方案2】:

_.union() 应用于父数组:

var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]];

var result = _.union.apply(_, testArray);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

如果支持 ES6,则使用 array spread

const testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]];

const result = _.union(...testArray);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

【讨论】:

    【解决方案3】:

    在 ES6 中,您可以使用扩展语法 ...Set 来做到这一点

    var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]
    
    var result = [...new Set([].concat(...testArray))];
    console.log(result)

    【讨论】:

      【解决方案4】:

      您可以拨打_.union.apply(null, arrays)。它记录在这里:

      https://lodash.com/docs/#union

      > var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]
      > lodash.union.apply(null, testArray)
      [ 1, 2, 3, 4, 5, 6, 7, 8, 10, 9 ]
      

      应用技巧是将数组数组转换为函数调用参数。如果您还需要对其进行排序,您可以在其末尾添加.sort()

      【讨论】:

        【解决方案5】:

        如果你需要,只在 ES5 中:

        var flattened = Object.keys(testArray.reduce(function(acc, cur) {
          cur.forEach(function(v) {acc[v] = true;});
          return acc;
        }, {})).sort(function(a, b) {return a - b;});
        

        【讨论】:

          猜你喜欢
          • 2018-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多