pushing all duplicate values in array to new array

I am trying to get result [1,1,1,1,2,2,20,20] out of below array.

Basically, I am trying to push all duplicate values in new array,However not getting the desired result. Request you to help.

const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

const dupArray = (arr) => {
  let newArray = array.sort();
  let filteredArray = [];
  for (y = 0; y < newArray.length; y++) {
    for (i = y + 1; i < newArray.length; i++) {
      if (newArray[y] === newArray[i]) {
        filteredArray.push(newArray[i]);
      }
    }
  }

  return filteredArray
};

console.log(dupArray());

1 thought on “pushing all duplicate values in array to new array”

Leave a Comment