DEV Community

Discussion on: A common coding interview question

Collapse
 
artezan profile image
artezan

I used for loop so that improve the performance


const input = ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
function FindIntersection(strArr) {
  const inBothStrings = []
   const [arr1,arr2] = strArr.map(item => item.split(", "))

  for (let index = 0; index < arr1.length; index++) {
    const element1 = arr1[index];
    const indexFound= arr2.findIndex(element2 => element2 === element1)

    if (indexFound !== -1) {
      inBothStrings.push(element1)
      arr2.splice(indexFound, 1)
    }
  }
  return inBothStrings.length ? inBothStrings.join(',') : false 
}
console.log(FindIntersection(input))