gpt4 book ai didi

javascript - 将两个数组与范围组合

转载 作者:行者123 更新时间:2023-11-30 21:05:20 26 4
gpt4 key购买 nike

我正在尝试合并两个数组。这些数组中的每一个都有定义范围的子数组。我想将它结合起来,以便创建的新数组反射(reflect)基于两个数组中的值的新范围。示例:

//I would like to create a new array based on the ranges in a and b.
var a = [[0, 20], [20, 40], [40, 70]];
var b = [[10, 25], [25, 35]]

//The result reflects the new ranges based on values in both the arrays.
var result = [[0, 10], [10, 20], [20, 25], [25, 35], [35, 40], [40, 70]]

最佳答案

您可以收集一个对象中的所有值,对其进行排序并从中构建元组。

var a = [[0, 20], [20, 40], [40, 70]],
b = [[10, 25], [25, 35]],
values = Object.create(null),
result = [];

a.concat(b).forEach(function (a) {
values[a[0]] = true;
values[a[1]] = true;
});

Object
.keys(values)
.map(Number)
.sort(function (a, b) {
return a - b;
})
.reduce(function (a, b) {
result.push([a, b]);
return b;
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将两个数组与范围组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691811/

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