javascript - 如何对数据进行分组?
问题描述
如何编写脚本将数组的元素分组为数组数组(或数组对象),其中最后一个是按顺序分组的元素数组。
如果下一个元素 Id 是序列的一部分,则它属于 prev 组,否则将创建新数组并且元素将落入其中。
如果元素 Id 高于 prev 元素的 Id 大于 1 - 是相同的序列 = 当前数组。
如果元素 ID 高于上一个元素的 ID 大于 2 - 是下一个序列 = 下一个(新)数组。
如果来自所有方面的元素邻居 Id 都大于当前 Id - 当前元素将创建一个包含自身的数组,并且它的键将是它自己的 Id。
无论结果是数组还是对象 - 生成键很容易,但现在对我来说组元素很难。
你可以尝试用 JavaScript 编写,甚至可以使用 Lodash 库。
const data = [
{id: 1},
{id: 2},
{id: 3},
{id: 7},
{id: 9},
{id: 10},
{id: 12},
{id: 14},
{id: 15},
{id: 16}];
===========================================
const result = [
0/"1-4": [
{id: 1},
{id: 2},
{id: 3},
{id: 4}],
1/"7": [
{id: 7}],
2/"9-10": [
{id: 9},
{id: 10}],
3/"12": [
{id: 12}],
4/"14-16": [
{id: 14},
{id: 15},
{id: 16}]];
解决方案
您可以使用 reduce 创建一个数组数组,其中下一个预期数字是当前项目 id 加一。
const data = [
{id: 1},
{id: 2},
{id: 3},
{id: 7},
{id: 9},
{id: 10},
{id: 12},
{id: 14},
{id: 15},
{id: 16}]
.sort((a,b)=>a.id-b.id)//make sure it is sorted by id
.reduce(
([result,nextNum],item)=>{//nextNum is the next expected number
if(nextNum===undefined){//first time nextNum is undefined
nextNum=item.id;//set nextNum to id of current item
result.push([]);//add empty array
}
if(!(nextNum===item.id)){//current item id is not the expected next number
result.push([]);//add empty array
}
result[result.length-1].push(item);//add item to last array of the array of arrays
return [result,item.id+1];//next expected number is current item id + 1
},
[[],undefined]//initial values for result and nextNum
);
console.log(data)
推荐阅读
- angular - 两种方式绑定在 userModel 上不起作用
- machine-learning - 了解隐藏层、感知器、MLP
- css - 带有ngFor的Ionic 4水平滚动
- php - 我可以通过soapCall获得属性值吗?
- python - 将生成的大型控制台输出写入文本文件中包含“...”而不是完整输出
- python-3.x - 在 Mac OS 10.12.6 中将 python 2 更改为 python 3
- java - 我应该使用 mp3 标签编辑器还是在 MediaStore 中插入新值?
- css - 在本机反应中顺利增加高度?
- python - 带有描述符的类型提示
- javascript - 更新elasticsearch中的多个文档?