【问题标题】:Loop over array and create `n` other arrays based on item value in array循环数组并根据数组中的项值创建“n”个其他数组
【发布时间】:2020-05-31 17:57:25
【问题描述】:

我喜欢循环一个长度未知和(某些)内容未知的对象数组,并创建一组新的枚举数组。

我知道数组有一组一致的键:值对,我想使用引用来分块数组。

这是示例数组:

[{something:test,value:10},{something:example,value:20},{something:test,value:30}]

该函数应该识别键'something'并根据相应值的变化创建许多数组,例如,在这种情况下,2个数组将产生一个对象形式:

{
    test: [{something:test,value:10},{something:test,value:30},
    example: [{something:example,value:20}]
}

换句话说,我需要根据数组中的某些项目值而不是大小/长度来分块数组。

我已经考虑/尝试使用索引值等来获取大小参数,但这似乎是一项艰巨的任务,我确信有更快的解决方案。

Lodash 等在他们的库中似乎没有这样的东西。

【问题讨论】:

    标签: javascript arrays loops


    【解决方案1】:

    你可以reduce它:

    var data=[{something:'test',value:10},{something:'example',value:20},{something:'test',value:30}];
    
    var result = data.reduce((acc, {something, ...rest})=>{
       acc[something] = acc[something] || [];
       acc[something].push({something, ...rest});
       return acc;
    },{});
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      听起来很简单reduce。比如:

      const input = [{something:"test",value:10},{something:"example",value:20},{something:"test",value:30}];
      
      const output = input.reduce((a, c) => {
        if (!Array.isArray(a[c.something])) {
          a[c.something] = [];
        }
        a[c.something].push(c);
        return a;
      }, {});
      
      console.log(output);

      【讨论】:

        【解决方案3】:

        您可以使用 Array.reduce() 并将对象推入数组。

        const arr = [{something:'test',value:10},{something:'example',value:20},{something:'test',value:30}]
        
        const result = arr.reduce((acc,cur) => {
            if(!Object.keys(acc).some(key => key === cur.something)){
                acc[cur.something] = [cur]
            }else{
                acc[cur.something].push(cur)
            }
            return acc
        },{})
        
        console.log(result)

        【讨论】:

          【解决方案4】:

          Object.Keys 将允许您从每个对象中获取所有键。 由于某些内容是未知的,因此不可能知道所有对象是否都具有某些链接属性,例如示例中的 something 道具。

          我想我需要另一个包含未知/变体内容的示例。因为您似乎可以遍历内容来检测您感兴趣的道具。如果您不提前知道道具并且正在根据最常见的道具进行操作,那么 Object.keys 函数应该可以帮助您。我想应该是这样的。

          function enumArrays(arrayObjects){
              let enumArrays = {}
              let keyCounts = {}
          
              // look at each object and get a count of the keys
              for (let obj of arrayObjects){
                  const keys = Object.Keys(obj);
                  for (let key of keys){
                      if (keyCounts.hasOwnProperty(key)){
                          keyCounts[key] += 1;
                      } else {
                          keyCounts[key] = 1;
                      }
                  }
              }
          
              //determine which key to use, there are plenty of ways to do this, but ill go with a basic approach
              let max = 0 // assuming positive integer counts only
              let selectedKey = "";
              for (let keyCount of Object.keys(keyCounts)){
                  if (keyCounts[keyCount] > max){
                      max = keyCounts[keyCount];
                      selectedKey = keyCount
                  }
              }
          
              //we now have our most common key in selected key! We can chunk the original array of Objects by that key
              enumArrays['null'] = [] // its possible that some objects will not have the selected key, so we'll store those objects in a null bucket
              for (let obj of arrayObjects){
                  if (obj[selectedKey]){
                      //check if prop type has been added yet
                      let propType = obj[selectedKey];
                      if (!enumArrays.hasOwnProperty(propType)){
                          //add an empty array to that propType
                          enumArrays[propType] = []
                      }
                      enumArrays[propType].push(obj)
                  } else {
                      enumArrays['null'].push(obj)
                  }
              }
          
              return enumArrays
          }
          

          【讨论】:

            猜你喜欢
            • 2012-06-25
            • 2012-10-08
            • 1970-01-01
            • 2021-07-11
            • 2020-07-04
            • 1970-01-01
            • 2023-01-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多