合并多个数组,并列给定的键。

问题描述 投票:0回答:1

我有三个对象。

V1 = [[a, 2, 4], 
      [b, 5, 5],
      [c, 4, 1]]

V2 = [[b, 1, 7], 
      [c, 3, 8],
      [d, 5, 4]]

V3 = [[a, 5, 2], 
      [b, 0, 9],
      [d, 3, 1]]

我希望输出是这样的。

[[a,2,4,0,0,5,2],
 [b,5,5,1,7,0,9],
 [c,4,1,3,8,0,0],
 [d,0,0,5,4,3,1]]

我该如何实现呢?

javascript d3.js plotly
1个回答
0
投票

这将会工作,但它不是超级漂亮;)

const flattenSiblings = (...plots) => {
   return plots.reduce((acc, c, i) => {
        c.flat();
        acc.push(...c);
        // return the array sorted alphabetically by its first element
        return acc.sort((a ,b) => ((a[0] > b[0]) && +1, (a[0] < b[0]) && -1));
    }, []);
}

let f = flattenSiblings(V1, V2, V3);

/* 
Hardcoded concatenation of the desired result since 
the pattern of how 0,0 should be inserted was not defined.
*/
let result = [
    [
        ...f[0].flat(),
        ...[0,0],
        ...f[1].slice(1,3).flat()
    ],
    [
        ...f[2].flat(),
        ...f[3].slice(1,3).flat(),
        ...f[4].slice(1,3).flat()
    ],
    [
        ...f[5].flat(),
        ...f[6].slice(1,3).flat(),
        ...[0,0]  
    ],
    [
        f[7][0],
        ...[0,0],
        ...f[7].slice(1,3).flat(),
        ...f[8].slice(1,3).flat() 
    ]
];

0
投票

你可以把值收集到一个对象中,然后用一个默认值为空的数组来分配收集到的值。

var v1 = [['a', 2, 4], ['b', 5, 5], ['c', 4, 1]],
    v2 = [['b', 1, 7], ['c', 3, 8], ['d', 5, 4]],
    v3 = [['a', 5, 2], ['b', 0, 9], ['d', 3, 1]],
    parts = [v1, v2, v3],
    empty = Array(parts.length * 2 + 1).fill(0);
    temp = parts.reduce((r, a, i) => {
        a.forEach(([key, ...values]) => {
            r[key] = r[key] || { 0: key };
            for (let j = 0; j < values.length; j++) {
                r[key][i * values.length + j + 1] = values[j];
            }
        });
        return r;
    }, {}),
    result = Object.values(temp).map(v => Object.assign([], empty, v));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.