首页 > 解决方案 > 数字列表到数字列表

问题描述

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

[[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>

标签: javascriptjqueryarraysfilterarrow-functions

解决方案


一种方法可以使用reduce()来完成,其中setaccumulator

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;}


推荐阅读