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

后端 未结 6 814
后悔当初
后悔当初 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:15

    You can use Object.reduce, Object.entries for this like below

    var array = [[1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]];
    
    
    let res = Object.entries(
                array.reduce((o, d) => {
                  let key = d.join('-')
                  o[key] = (o[key] || 0) + 1
    
                  return o
              }, {}))
              .flatMap(([k, v]) => v > 2 ? [k.split('-').map(Number)] : [])
      
      
    console.log(res)

    OR may be just with Array.filters

    var array = [[1, 17], [1, 17], [1, 17], [1, 17], [2, 12], [5, 9], [2, 12], [6, 2], [2, 12]];
    
    let temp = {}
    let res = array.filter(d => {
      let key = d.join('-')
      temp[key] = (temp[key] || 0) + 1
      
      return temp[key] == 3
    })
    
    console.log(res)

提交回复
热议问题