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

后端 未结 6 854
后悔当初
后悔当初 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条回答
  •  鱼传尺愫
    2020-12-03 19:19

    For a different take, you can first sort your list, then loop through once and pull out the elements that meet your requirement. This will probably be faster than stringifying keys from the array even with the sort:

    var arr = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]]
    arr.sort((a, b) => a[0] - b[0] || a[1] - b[1])
    
    // define equal for array
    const equal = (arr1, arr2) => arr1.every((n, j) => n === arr2[j])
    
    let GROUP_SIZE = 3
    first = 0, last = 1, res = []
    
    while(last < arr.length){
        if (equal(arr[first], arr[last])) last++
        else {
            if (last - first >= GROUP_SIZE)  res.push(arr[first])
            first = last
        }
    }
    if (last - first >= GROUP_SIZE)  res.push(arr[first])
    console.log(res)

提交回复
热议问题