Find if two arrays are repeated in array and then select them

后端 未结 6 833
后悔当初
后悔当初 2020-12-03 18:51

I have multiple arrays in a main/parent array like this:

var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]];
<
6条回答
  •  Happy的楠姐
    2020-12-03 19:14

    You could take a Map with stringified arrays and count, then filter by count and restore the arrays.

    var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]],
        result = Array
            .from(array.reduce(
                (map, array) =>
                    (json => map.set(json, (map.get(json) || 0) + 1))
                    (JSON.stringify(array)),
                new Map
             ))
            .filter(([, count]) => count > 2)
            .map(([json]) => JSON.parse(json));
            
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Filter with a map at wanted count.

    var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]],
        result = array.filter(
            (map => a => 
                (json =>
                    (count => map.set(json, count) && !(2 - count))
                    (1 + map.get(json) || 1)
                )
                (JSON.stringify(a))
            )
            (new Map)
        );
            
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Unique!

    var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]],
        result = array.filter(
            (s => a => (j => !s.has(j) && s.add(j))(JSON.stringify(a)))
            (new Set)
        );
            
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题