javascript - 文章数组根据使用 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 个数组(一个带有标记,一个带有视频),它没有记住原始数据的顺序,也没有根据顺序创建所有数据组的单独数组。
解决这个问题的最优雅的方法是什么?如果您能引导我朝着正确的方向前进,我将不胜感激。
解决方案
您可以使用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; }
推荐阅读
- angular - 在 IE11 中读取 readAsBinaryString
- typescript - 如何清理打字稿缓存?
- scala - 用于激励 scala 完全面向对象的替代布尔类
- vue.js - 在 vue.js 中附加组件并访问子组件的值
- authentication - 如何将 Windows 身份验证和 JWT 与 .Net Core 2.1 结合使用
- html - 将图像直接放在彼此下方(DIV/CSS)
- mysql - 将 SQL 查询转换为 Codeigniter
- android - Android:为除应用程序音频流之外的所有通知设置“请勿打扰”(setInterruptionFilter)
- chef-infra - 在节点中安装厨师后出现错误
- kotlin - Kotlin/Native 中的 .freeze() 是什么?