首页 > 解决方案 > 文章数组根据使用 Javascript 减少的主题拆分为子数组

问题描述

我正在尝试根据第一个键值对将文章数组拆分为子数组,并且它的顺序。

我查看了许多 Stack Overflow 帖子,我认为这是最适合我想要完成的内容的帖子:

根据属性将对象数组分解为单独的数组

我知道通常会问有关 reduce 的问题,但我被绊倒了,这就是我找不到答案的原因:

有什么不同:我不想将数组过滤为 2 个单独的类别(即“标记”和“视频”),而是让第一个数组是所有“标记”项,直到一个“视频”项,使一个包含所有“视频”项目的数组,直到下一个“标记”项目,创建一个包含所有“标记”项目的新数组,直到下一个“视频”项目,等等。

这是一个重现我正在尝试做的事情的 REPL: REPL 重现问题

数据如下所示:

export default [{
  "type": "markup",
  "element": "p",
  "html": "blah"
}, {
  "type": "markup",
  "element": "p",
  "html": "blah"
}, {
  "type": "markup",
  "element": "p",
  "html": "blah"
}, {
  "type": "embeddedVideo",
  "element": "p",
  "html": "embeddedWidget"
}, {
  "type": "markup",
  "element": "p",
  "html": "blah"
},
{
  "type": "markup",
  "element": "p",
  "html": "blah"
},
]

在使用 JavaScript reduce 后,我希望它看起来像:

[
  [
    {type: 'markup', element: 'p', html: 'blah' /*...*/ },
    {type: 'markup', element: 'p', html: 'blah' /*...*/ },
    {type: 'markup', element: 'p', html: 'blah' /*...*/ }
  ],
  [
    {type: 'embeddedVideo', /*...*/ }
  ],
  [
    {type: 'markup', element: 'p', html: 'blah' /*...*/ },
    {type: 'markup', element: 'p', html: 'blah' /*...*/ },
    {type: 'markup', element: 'p', html: 'blah' /*...*/ }
  ]
]

到目前为止,我所拥有的是:

import articleBody from './articleBody.js';


 function groupBy(arr, property) {
  return arr.reduce((prop, x) => {
    if (!prop[x[property]]) { prop[x[property]] = []; }
    prop[x[property]].push(x);
    return prop;
  }, {});
}

let outputSample = groupBy(articleBody, "type");

console.log(outputSample)

这段代码只是创建了 2 个数组(一个带有标记,一个带有视频),它没有记住原始数据的顺序,也没有根据顺序创建所有数据组的单独数组。

解决这个问题的最优雅的方法是什么?如果您能引导我朝着正确的方向前进,我将不胜感激。

标签: javascriptarraysmultidimensional-arrayreduce

解决方案


您可以使用Array#reduce并检查累加器的最后一个元素。

var array = [{ type: "markup", element: "p", html: "blah" }, { type: "markup", element: "p", html: "blah" }, { type: "markup", element: "p", html: "blah" }, { type: "embeddedVideo", element: "p", html: "embeddedWidget" }, { type: "markup", element: "p", html: "blah" }],
    grouped = array.reduce((r, o, i, a) => {
        var last = r[r.length - 1];
        if (!last || last[0].type !== o.type) {
            r.push([o]);
        } else {
            last.push(o);
        }
        return r;
    }, []);

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


推荐阅读