对Javascript数组进行分组

Group a Javascript Array(对Javascript数组进行分组)

本文介绍了对Javascript数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一个数组中获取数据,按对象属性对数据进行分组,然后将其发送到新的数组。当前数据格式如下:
const data = [
    {
        "dataId": "1",
        "tableName": "table1",
        "column": "firstHeader",
        "rows": [
            "a","b","c"
        ]
    },
    {
        "dataId": "2",
        "tableName": "table1",
        "column": "secondHeader",
        "rows": [
            "d","e","f",
        ]
    },
    {
        "dataId": "3",
        "tableName": "table2",
        "column": "aNewFirstHeader",
        "rows": [
            1,2,3
        ]
    }
];

我使用了Lodashgroupby方法,该方法以接近我期望的格式对项进行分组,但不完全是我想要的最终结果。Lotash结果为:

[
    [
        { "tableName": 'table1',
            "dataId": '1',
            "header": 'firstHeader',
            "rows": ["a","b","c"]
        },

        { "tableName": 'table1',
            "dataId": '1',
            "header": 'secondHeader',
            "rows": ["d","e","f"]
        }
    ],

    [
        { "tableName": 'table2',
            "dataId": '2',
            "header": 'aNewFirstHeader',
            "rows": [1,2,3] },
    ]
]

最终,我要寻找的是最终结果:

[
    {
    "tableName": "table1",
    "column": ["firstHeader", "secondHeader"],
    "rows": [["a","b","c"], ["d","e","f"]]
    },
    {
    "tableName": "table2",
    "column": ["aNewFirstHeader"],
    "rows": [[1,2,3]]
    }
]

有没有不同的方法来使用groupBy方法,或者可能是仅使用javascript方法来获得我正在寻找的最终结果?

推荐答案

通过使用reducefindIndex,我们可以在O(N)时间内重建适合您格式的新数组。

data.reduce((arr, record) => {
  const index = arr.findIndex((inside) => (inside.tableName === record.tableName));

  if (index === -1) { 
    arr.push({
        tableName: record.tableName,
        column: [record.column],
        rows: [record.rows]
    }) 
  } else {
    arr[index].column.push(record.column);
    arr[index].rows.push(record.rows);
  }

  return arr;
}, []);
const data = [
{
    "dataId": "1",
    "tableName": "table1",
    "column": "firstHeader",
    "rows": [
        "a", "b", "c"
    ]
},
{
    "dataId": "2",
    "tableName": "table1",
    "column": "secondHeader",
    "rows": [
        "d", "e", "f",
    ]
},
{
    "dataId": "3",
    "tableName": "table2",
    "column": "aNewFirstHeader",
    "rows": [
        1, 2, 3
    ]
}
];

const newData = data.reduce((arr, record) => {
  const index = arr.findIndex((inside) => (inside.tableName === record.tableName));

  if (index === -1) { 
	arr.push({
        tableName: record.tableName,
		column: [record.column],
		rows: [record.rows]
	}) 
  } else {
	arr[index].column.push(record.column);
    arr[index].rows.push(record.rows);
  }
  return arr;

}, []);

console.log(newData);

这篇关于对Javascript数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:对Javascript数组进行分组

基础教程推荐