gpt4 book ai didi

javascript - 数字列表到数字列表

转载 作者:行者123 更新时间:2023-11-30 19:50:12 25 4
gpt4 key购买 nike

我有一个数字列表,格式如下:

[[1,2],[3,4],[5,1]]

我期待得到下一个输出:

[1,2,3,4,5]

这是我当前方法的一个示例:

<!DOCTYPE html>
<html>
<head>
<title>Expected - [1,2,3,4,5,6,7,8,9,10]</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Expected - [1,2,3,4,5,6,7,8,9,10];
var array_of_arrays = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
console.log(array_of_arrays);

// Section 1 - code does what I expect. I would like something like Section 2.
var array_of_values = [];
array_of_arrays.map((x) => {
x.map((y) => {
if (array_of_values.indexOf(y) == -1)
array_of_values.push(y)
})
});
console.log(array_of_values);

// Section 2 - This code does not do what I expect.
var resp = array_of_arrays.map(x => x.map(y => y));
console.log(resp);
});
</script>
</body>
</html>

最佳答案

一种方法可以使用 reduce() 来完成用set作为累加器:

let input = [[1,2],[3,4],[5,1]];

let res = input.reduce((acc, a) =>
{
a.forEach(x => acc.add(x));
return acc;
}, new Set());

console.log(Array.from(res));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

另一种方法是使用新的 flat()方法:

let input = [[1,2],[3,4],[5,1]];
let res = new Set(input.flat());
console.log(Array.from(res));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

关于javascript - 数字列表到数字列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54561375/

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