数字列表到数字列表

时间:2019-02-06 19:42:43

标签: javascript jquery arrays filter arrow-functions

数字列表到数字列表[[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]]

6 个答案:

答案 0 :(得分:1)

我将使用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));

或使用实验性的flat()

let input = [[1,2],[3,4],[5,1]];
let res = new Set(input.flat());
console.log(Array.from(res));

答案 1 :(得分: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());

答案 2 :(得分: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);

答案 3 :(得分: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)
);

答案 4 :(得分:0)

这是您想要的吗?

阅读评论

WHERE deleted = 0  AND  the_datetime > NOW() - INTERVAL 7 DAY
INDEX(deleted, the_datetime)

答案 5 :(得分:0)

您可以使用reduce并将Set对象作为初始值,并将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());