【问题标题】:Javascript; Compress array with distinct values/countJavascript;压缩具有不同值/计数的数组
【发布时间】:2021-03-05 10:56:54
【问题描述】:

我得到了一个我正在研究的谜题。我在 Javascript 中得到了一个看起来像这样的多维数组; 每个特征都有一个 ID、一个日期(字符串)和一个状态

例如;

Features = [
    [1, "20200503", "Active"],
    [2, "20200503", "Closed"],
    [2, "20200503", "Closed"],
    [2, "20200502", "Closed"],
    [2, "20200501", "Active"],
    [2, "20200430", "Active"],
    [2, "20200430", "Active"],
    [3, "20200503", "New"],
    [3, "20200502", "New"],
];

我想将此数组压缩成一个我想要的新数组;

Features = [
    [1, 1, "Active"],
    [2, 3, "Closed"],
    [2, 3, "Active"],
    [3, 2, "New"],
];

我想对 ID 和状态进行区分并计算日期。

是否有可能在 Javascript 中做到这一点?

【问题讨论】:

    标签: javascript arrays count distinct


    【解决方案1】:

    你想要做的是将reduce 数组变成一个更小的数组。好吧,有一个功能!您可以传递一个空数组作为 reduce 函数的第二个参数,以将其用作累加器,并将光标与前一个元素进行比较,以了解如何处理它。

    features = features.reduce((acc, cur, index, arr) => {
      let prev = arr[index - 1];
    
      if (index === 0 || cur[0] !== prev[0] || cur[2] !== prev[2]) acc.push([cur[0], 1, cur[2]]);
      else acc[acc.length - 1][1]++;
    
      return acc;
    }, []);
    

    【讨论】:

      【解决方案2】:
      function compress(features) {
          // First get unique Ids and states
          var ids = new Set(features.map(f => f[0]);
          var states = new Set(features.map(f => f[2]);
      
          // Array in which we will store the result
          const result = [];
      
          // Next loop through to make every permutation for the IDs and States 
          for (const id of ids) {
              for (const state of states) {
                  // Get number of features with id and state
                  let featureCount = features.filter(f => f[0] === id && f[2] === state).length;
                  
                  // check if there are any with ID "id" and State "state"
                  if (featureCount > 0)
                      result.push([id, featureCount, state]);
              }
          }
          
          return result;
      }
      

      那就这样称呼吧

      var compressedFeatures = compress(Features);
      

      【讨论】:

      • 嗨,这似乎有效,谢谢!但是还有一个问题;如果我向要压缩的数组添加更多值怎么办?例如:[1, "20200503", "Jim", "Active"][1, "20200503", "John", "Active"][1, "20200503, "John", "Active"] 有没有办法计算日期和名字?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 2022-01-13
      • 2011-09-05
      • 1970-01-01
      相关资源
      最近更新 更多