我有使用以下格式的数字列表:
[[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>
这就是您想要的。
阅读评论
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)
一种解决方法可以使用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;}
您可以使用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);
您可以创建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)
);
您可以使用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());
您可以使用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());