首页 > 解决方案 > 如何对数据进行分组?

问题描述

如何编写脚本将数组的元素分组为数组数组(或数组对象),其中最后一个是按顺序分组的元素数组。

如果下一个元素 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}]];

标签: javascriptecmascript-6lodash

解决方案


您可以使用 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)


推荐阅读