javascript - 数字列表到数字列表
问题描述
我有一个数字列表,格式如下:
[[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为accumulator
:
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 - 在 Google 表格中提交后弹出表单不会关闭
- reactjs - 有没有办法创建一种通用方法来减少状态类似操作的代码量?
- symfony - Symfony 路线。无法设置注释
- bash - Bash 比较值
- ckeditor - #9073 ImageUpload 回调不能跨域调用 CKEditor
- r - 如何在 R 中提取两列数据
- roblox - Roblox 中的排行榜类而不是 KO
- javascript - 组合html文档时JavaScript计算输出错误(html干扰?)
- r - overlay() 函数中的错误,用 R 中的栅格和数值计算
- javascript - 数组架构上的 Node.js RESTful API 验证错误