Search code examples
javascriptsequencereduceindexof

Can't find the longest occurancy in a set of duplicates


The target is to detect superstring in a set of arrays. In this case it should be 'bal' but I get 'lbal'.

  const arr = [
  ['g', 'l', 'o', 'b', 'a', 'l'],
  ['b','a','l','l']
  ]

const res = argv.reduce((acc, val) => acc.filter(elem => val.includes(elem)))

This function just gives ALL duplicates(items that are presented in any array) when I need only the most long duplicate sequence. Any suggestions?


Solution

  •   const original = [
      ['a', 'b', 'm'],
      ['g', 'o', 'a', 'b'],
      ['w', 'o', 'u', 'k', 'a', 'b']
      ]
      
      
      // The easiest is to split up between unique results and duplicates
      let uniqueValues = []
      let duplicates = []
      
     // Now we're going to loop every array
     original.forEach((arr) => {
      // Loop every value inside the array
      arr.forEach((value) => {
        // Check if we had this value already
        if (!uniqueValues.includes(value)) {
          uniqueValues.push(value)
        } else {
          duplicates.push(value)
        }
      })
     })
     
    console.log('Duplicates: ', duplicates)
    
    // If you want remove the duplicates from the duplicates, use set
    
    let uniqueDuplicates = [...new Set(duplicates)]
    
    console.log('Unique duplicates: ', uniqueDuplicates)