数字列表到数字列表[[1,2,3,4,5,1]]预期[1,2,3,4,5]
array.filter(),array.map()
<!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>
结果错误=> [[1,2],[3,4],[5,6],[7,8],[9,10],[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]];
// 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)