DEV Community

nikhilkalariya
nikhilkalariya

Posted on

Duplicate Number

Find duplicate number with filter

const array = [1, 2, 3, 2, 4, 5, 4, 5];
const duplicates1 = array.filter((item, index) => array.indexOf(item) !== index);

console.log(duplicates1); // Output: [2, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Find duplicate number with Nested For In Loop

const array = [1, 2, 3, 2, 4, 5, 4, 5];
let duplicates = [];

for (let i in array) {
    for (let j in array) {
        if (array[i] === array[j] && i !== j) {
            // Check if the found duplicate is already in the duplicates array
            if (!duplicates.includes(array[i])) {
                duplicates.push(array[i]);
                break; // To avoid adding the same duplicate multiple times
            }
        }
    }
}

console.log(duplicates);
Enter fullscreen mode Exit fullscreen mode

Find duplicate number with Foreach

let arr = [1, 2, 3, 4, 5, 2, 6, 3, 7, 8, 8];
let duplicates = [];

arr.forEach(function (value, index, array) {
    if (array.indexOf(value, index + 1) !== -1
        && duplicates.indexOf(value) === -1) {
        duplicates.push(value);
    }
});
console.log(duplicate)
Enter fullscreen mode Exit fullscreen mode

Find duplicate number Using Set() object and has() Method

const array = [1, 2, 3, 2, 4, 5, 4, 5];
const uniqueElements = new Set();
const duplicates = [];

array.forEach(item => {
  if (uniqueElements.has(item)) {
    duplicates.push(item);
  } else {
    uniqueElements.add(item);
  }
});

console.log(duplicates); // Output: [2, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Removing Duplicates from an Array In-Place:

function removeDuplicates(nums) {
    let index = 1;
    for (let i = 1; i < nums.length; i++) {
        if (nums[i] !== nums[i - 1]) {
            nums[index] = nums[i];
            index++;
        }
    }
    return nums.slice(0, index);
}

console.log(removeDuplicates([1, 1, 2, 2, 3, 4, 4])); // Example output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Removing Duplicates from an Array Without Using Any Library:

function removeDuplicates(arr) {
    const uniqueElements = [];
    for (let i = 0; i < arr.length; i++) {
        if (!uniqueElements.includes(arr[i])) {
            uniqueElements.push(arr[i]);
        }
    }
    return uniqueElements;
}

const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = removeDuplicates(arrayWithDuplicates);
console.log(uniqueArray); // Example output: [1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

Removing Duplicates from an Array Without Using Any Library second:

function removeDuplicates(arr) {
    const unique = [];
    for (const num of arr) {
        if (!unique.includes(num)) {
            unique.push(num);
        }
    }
    return unique;
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Example output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)