DEV Community

Discussion on: Find duplicate or repeat elements in js array

Collapse
 
jord profile image
Jordan Turner

This doesn't help at all, this only returns a bool true or false. How do you return all the duplicate elements of the array into a new array?

Collapse
 
beko09 profile image
abobaker hilal • Edited

you can use

function duplicateItem(arr) {
 let itemCountObj = {};
  let maxItem = []
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    itemCountObj[item] = itemCountObj[item] + 1 || 1;
    if (itemCountObj[item] >= 2) {
      maxItem.push(item);
    }
  }
  return maxItem;
}
Enter fullscreen mode Exit fullscreen mode