How to extract the unique integers from an array excluding duplicates in JavaScript

1 Answer

0 votes
function getUniqueExcludeDuplicates(arr) {
    // Object to count occurrences of each number
    const frequency = {};

    // Count frequencies of each number in the array
    arr.forEach(num => {
        frequency[num] = (frequency[num] || 0) + 1;
    });

    // Collect numbers that appear only once
    const result = arr.filter(num => frequency[num] === 1);

    return result;
}

const arr = [1, 2, 3, 5, 8, 3, 1, 1, 0, 6, 5, 7, 3, 1, 4, 9];

const uniqueValues = getUniqueExcludeDuplicates(arr);

console.log("Unique values (excluding duplicates):", uniqueValues.join(" "));


   
/*
run:
    
Unique values (excluding duplicates): 2 8 0 6 7 4 9
       
*/

 



answered Mar 29 by avibootz
...