gpt4 book ai didi

javascript - 在同一索引中将公共(public)数组元素对齐在一起

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:10 24 4
gpt4 key购买 nike

鉴于此输入:

[
['a', 'b', 'c']
['b', 'c', 'd']
['a', 'd', 'b']
]

我想返回这个输出:

[
['a', 'b', 'c']
[null, 'b', 'c', 'd']
['a', 'b', null, 'd']
]

使得每个数组中的每个匹配字符串都在数组中的相同位置,任何间隙都是空值。

上下文

enter image description here

我需要像上面那样渲染一堆任意字符串,但要确保列之间的每个公共(public)字符串都渲染在同一水平线上。在此示例中,每个数组都是上图中的一列。一旦我正确设置了底层数组,我就可以使用简单的循环将字符串呈现在正确的位置。

最佳答案

您可以使用 reduce() 方法和一个 ES6 Set 来保持当前值。

const input = [['a', 'b', 'c'],['b', 'c', 'd'],['a', 'd', 'b']]

const all = new Set
const result = input.reduce((r, arr) => {
arr.forEach(e => all.add(e))
r.push([...all].sort().map(e => arr.includes(e) ? e : null))
return r;
}, []);

console.log(result)

关于javascript - 在同一索引中将公共(public)数组元素对齐在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49944658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com