数字列表到数字列表

问题描述 投票:1回答:6

我有使用以下格式的数字列表:

[[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>
javascript jquery arrays filter arrow-functions
6个回答
1
投票

这就是您想要的。

阅读评论

var array_of_arrays = [[1, 2],[3, 4], [5, 6], [7, 8], [9, 10], [1, 2],[3, 4], [5, 6], [7, 8], [9, 10]];
// flat the array and then select distinct after that sort the array out
var arr = array_of_arrays.flatMap((x)=>x).filter((x, i, a) => a.indexOf(x) == i).sort((a,b)=> a-b)

console.log(arr)

2
投票

一种解决方法可以使用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;}

1
投票

您可以使用Array.prototype.reduce()Set

来做到这一点

let arr = [[1,2],[3,4],[5,1]]
//flatting array
arr = arr.reduce((ac,item) => ([...ac,...item]),[])
//remove dupliactes
arr = [...new Set(arr)];
console.log(arr);

0
投票

您可以创建distinct过滤器并使用flatMap

const distinct = (value, index, self) => {
  return self.indexOf(value) == index;
}

console.log(
  [[1,2],[3,4],[5,6],[7,8],[9,10],[1,2],[3,4],[5,6],[7,8],[9,10]]
  .flatMap(x => x)
  .filter(distinct)
);

0
投票

您可以使用flatMap。它根据提供的回调函数展平(取消嵌套)数组。使用过滤器过滤掉重复项,并使用sort()

对它们进行排序

var a=[[1,2],[3,4],[5,1]].flatMap((x)=>x);
var arr=[];
console.log(a.filter((e)=>arr.indexOf(e)==-1?arr.push(e):false).sort());

0
投票

您可以使用reduce并将Set对象作为初始值传递,设置为唯一值。

 var list = [[1,2],[3,4],[5,1]];
 var arr = list.reduce((acc, c)=>{ c.map((a)=>{  acc.add(a) }); return acc; }, new Set());
© www.soinside.com 2019 - 2024. All rights reserved.