【问题标题】:Convert array of objects to array of arrays (by attribute)将对象数组转换为数组数组(按属性)
【发布时间】:2019-06-05 07:34:29
【问题描述】:

我想通过属性“icon”将我的数组转换为数组数组。

const array = [
  { icon: true }, 
  { icon: false },
  { icon: false }, 
  { icon: true }, 
  { icon: false }
]

我需要:

[[{icon: true}, {icon: false}, {icon: false}], [{{icon: true}, {icon: false}}]]

属性icon === true是新数组开始形成的标志。

我认为你应该使用reduce函数。

array.reduce((result, item, index) => { ... }, [])

如何最好地编写转换?谢谢!

【问题讨论】:

  • 请添加尝试过的内容。

标签: javascript arrays object ecmascript-6 reduce


【解决方案1】:

您可以使用.reduce()方法如下:

const data = [{ icon: true }, { icon: false }, { icon: false }, { icon: true }, { icon: false }]

const result = data.reduce((r, c) => {
  if(c.icon === true)
    r.push([c]);
  else
    r[Math.max(r.length - 1, 0)].push(c);
    
  return r;
},[]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 谢谢!这是完美的!
【解决方案2】:

您可以使用while 循环

const array = [{ icon: true }, { icon: false }, { icon: false }, { icon: true }, { icon: false }]
i = 0;
result = [];
aux = [];
while(i <  array.length){
   if(array[i].icon){
     if(aux.length !== 0){
        result.push(aux);
        aux = [array[i]];
     }
     else
        aux.push(array[i]);
   }
   else
     aux.push(array[i]);
   i++;
}
result.push(aux);
console.log(result);

【讨论】:

    【解决方案3】:

    您可以在数组上使用闭包进行插入。这可以防止查找数组中的最后一项。

    const
        data = [{ icon: true }, { icon: false }, { icon: false }, { icon: true }, { icon: false }],
        result = data.reduce((a => (r, o) => {
            if (o.icon) r.push(a = []);
            a.push(o);
            return r;
        })(), []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案4】:

      const array = [
        { icon: true },
        { icon: false },
        { icon: false },
        { icon: true },
        { icon: false }
      ];
      
      console.log(grouper(array));
      
      function grouper(array) {
        return array.reduce((acc, next) => {
          const entry = [next];
      
          if (next.icon) return acc.concat([entry]);
          const beforeNextCollection = acc.slice(0, acc.length - 1);
      
          const nextCollection = acc[acc.length - 1];
          const updatedCollection = nextCollection.concat(entry);
      
          return beforeNextCollection.concat([updatedCollection]);
        }, []);
      }

      【讨论】:

        猜你喜欢
        • 2020-05-14
        • 2022-12-08
        • 2016-03-22
        • 1970-01-01
        • 2019-02-10
        • 1970-01-01
        • 1970-01-01
        • 2020-06-15
        相关资源
        最近更新 更多