skip to Main Content

I came across a basic question of array in javascript of list out the recurring elements or duplicate elements in an array of strings.

So, lets say we have an array, arr = ['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan','Tom', 'John']

So now I tried to solve this by below approach:

var duplicate = [];

function duplicateValues (arr) {
   let l = arr.length;
   
   for (let i=0; i<l; i++){
      if(arr[i+1] == arr[i]) {
     duplicate.push(arr[i]);
   }
 }
   return duplicate;
}

duplicateValues(['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan','Tom', 'John']
);

Expected output:

['Ash', 'Bob', 'Dylan']

But I am getting an empty array in the console. What should be the best approach to solve this problem?

4

Answers


  1. This should be very simple, look below.

    const d = ['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan','Tom', 'John'];
    
    const dub = d.filter(x=> d.filter(f=> f ==x).length>1).reduce((a,v)=> {
      if(!a.find(x=> x == v))
          a.push(v)
        return a
    },[])
    console.log(dub)
    Login or Signup to reply.
  2. Wouldn’t that be easier?

    const array = ['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan', 'Tom', 'John']
    
    const result = [...new Set(array.filter((e, i, a) => a.indexOf(e, i + 1) !== -1))]
    
    console.log(result)
    Login or Signup to reply.
  3. All you need to do is to just check if a map has that key.

    const arr = ['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan', 'Tom', 'John']
    
    let map = new Map();
    
    const dups = arr.reduce((acc, curr) => {
      if (map.has(curr.toLowerCase()) && acc.indexOf(curr) == -1) {
        acc.push(curr)
      } else {
        map.set(curr.toLowerCase(), curr)
      }
    
      return acc;
    }, []);
    
    console.log(dups)
    Login or Signup to reply.
  4. You could use reduce to get the frequency of each name in the array, then filter only those entries that appear with a frequency of 2 or more.

    This approach avoids the use of find and indexOf, which would scan over the array an unnecessary number of times.

    const arr = ['Ash', 'Bob', 'Jarvis', 'Ash', 'Ash', 'Dylan', 'Bob', 'Dylan','Tom', 'John']
    
    console.log(Object.entries(arr.reduce((a,c)=>
      (a[c]??=0,a[c]++,a),{})).filter(([k,v])=>v>1).map(([k])=>k))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search