首页 > 解决方案 > 如何根据某些属性对javascript数组进行分组?

问题描述

我有一个像这样的对象的 JS 数组:

var myArray = [
  { line: 20, text: [31, 80] },
  { line: 10, text: [80, 22] }
]

行在整个 myArray 中是唯一的,每行都有一些文本(不是唯一的)。如何将每个文本与其对应的行匹配?

最终结果应该是这样的:

var myNewArray = [
  { text: 31, line: [20] },
  { text: 80, line: [20, 10] },
  { text: 22, line: [10] }
]

标签: javascriptarrayssortinglodash

解决方案


一些方法与Map.

结果你得到一个临时地图,它收集了所有text,按line. 要获取对象数组,请将键/值对映射为 eanted 属性。

  • 由于具有嵌套的数据数组,您需要 eiter 对数据进行规范化以获取单个line/text值,然后添加分组 by text

    const
        data = [{ line: 20, text: [31, 80] }, { line: 10, text: [80, 22] }],
        result = Array.from(
            data
                .flatMap(({ line, text }) => text.map(text => ({ text, line })))
                .reduce((m, { text, line }) => m.set(text, [...(m.get(text) || []), line]), new Map),
            ([text, line]) => ({ text, line })
        );
    
    console.log(result);

  • 或者一步完成,但使用减少外部 ( line) 和内部数组 (text数组) 的嵌套方法。

    const
        data = [
            { line: 20, text: [31, 80] },
            { line: 10, text: [80, 22] }
        ],
        result = Array.from(
            data.reduce(
                (m, { line, text }) => 
                    text.reduce(
                        (n, text) => n.set(text, [...(n.get(text) || []), line]),
                        m
                    ),
                new Map
            ),
            ([text, line]) => ({ text, line })
        );
    
    console.log(result);


推荐阅读