skip to Main Content

I have a two arrays which contains repeated characters. I tried to achieve it by using for loop in JavaScript.
I am getting output with repeated and also non repeated. which is not expected. I want only repeated characters in two arrays.

Thanks in advance.

I have a two arrays which contains repeated characters. I tried to achieve it by using for loop in JavaScript. I am getting output with repeated and also non repeated. which is not expected. I want only repeated characters in two arrays.

let arr1 = [1, 1, 2, 2, 3, 3, 4];
let arr2 = [1, 1, 2, 2, 7, 3, 3, 5, 6, 1];

function repeatedElements(inputArray1, inputArray2) {
  let repeatedEle = [];
  for (let ele of inputArray1) {
    if (inputArray1.indexOf(ele) !== inputArray2.lastIndexOf(ele)) {
      repeatedEle.push(ele)
    }
  }
  return [...new Set(repeatedEle)]
}
console.log(repeatedElements(arr1, arr2));

4

Answers


  1. let arr1 = [1, 1, 2, 2, 3, 3, 4,8,9]; 
    let arr2 = [1, 1, 2, 2, 7, 3, 3, 5, 6, 1]; 
    function repeatedElements(inputArray1, inputArray2){
      let repeatedEle = [];
      for(let ele of inputArray1){
        inputArray2.find((value)=>value==ele) ? 
            repeatedEle.push(inputArray2.find((value)=>value==ele)) : 
            ''
      }
      return [...new Set(repeatedEle)]
    }
    console.log(repeatedElements(arr1, arr2));
    
    Login or Signup to reply.
  2. Change your for loop to this:

    for (let ele of inputArray1) {
        if (inputArray2.includes(ele) && !repeatedEle.includes(ele)) {
          repeatedEle.push(ele);
        }
    }
    

    then return the array repeatedEle

    Login or Signup to reply.
  3. You need to loop through each array separately and check if the element is present more than once and then you can use Set two get the unique elements out of it.

    let arr1 = [1, 1, 2, 2, 3, 3, 4 ]; 
    let arr2 = [1, 1, 2, 2, 7, 3, 3, 5, 6, 1]; 
    function repeatedElements(inputArray1, inputArray2){
      let repeatedEle = [];
      for(let ele of inputArray1){
         if(inputArray1.indexOf(ele) !== inputArray1.lastIndexOf(ele)){
           repeatedEle.push(ele)
         }
      }
      for(let ele of inputArray2){
         if(inputArray2.indexOf(ele) !== inputArray2.lastIndexOf(ele)){
           repeatedEle.push(ele)
         }
      }
      return [...new Set(repeatedEle)]
    }
    console.log(repeatedElements(arr1, arr2));
    Login or Signup to reply.
  4. for the best efficient way, you can use loadsh [website][1]

    const _=require("lodash");
    let arr1 = [1, 1, 2, 2, 3, 3, 4];
    let arr2 = [1, 1, 2, 2, 7, 3, 3, 5, 6, 1];
    console.log(_.intersection(arr1,arr2));
    
    //output [1,2,3]
    
    
      [1]: https://lodash.com/docs/4.17.15#intersection
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search