LoginSignup
5
2

『配列をN個ずつに分割したい』みたいな時には Object.groupBy がとてもよい

Last updated at Posted at 2023-11-10

Object.groupByがとてもよい。

たとえば『配列をN個ずつに分割したい』みたいな時には、reduce()で書いたり、最近だとflatMap()で書いたりするが、わりと泥臭いというか可読性の悪いコードになりがちだった。
でも、まさかの時のObject.groupBy

    Object.values(Object.groupBy(
        ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",],
        (...[, i]) => Math.floor(i / 3)
    ));

// [
//     ["a", "b", "c"],
//     ["d", "e", "f"],
//     ["g", "h", "i"],
//     ["j"]
// ]

剰余にすれば、行列入れ替えバージョンも。

    Object.values(Object.groupBy(
        ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",],
        (...[, i]) => i % 3
    ));
    
// [
//     ["a", "d", "g", "j"],
//     ["b", "e", "h"],
//     ["c", "f", "i"]
// ]

ちょっと可読性がいまいちだけど、Python の zip関数もどきとか。

    const zip = (...args) => {
        const minLength = Math.min(...args.map(x => x.length));
        return Object.values(Object.groupBy(
            args.flatMap(x => x.slice(0, minLength)),
            (...[, i]) => i % minLength
        ))
    }

    zip(["a", "b", "c"], ["A", "B", "C", "D"], [0, 1, 2])

// [
//     ["a", "A", 0],
//     ["b", "B", 1],
//     ["c", "C", 2]
// ]
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2