How to print the distinct elements of an array in JavaScript

3 Answers

0 votes
function printUniqueElements(arr) {
    const object = {};
  
    arr.forEach(function (item) {
        if (!object[item])
             object[item] = 0;
        object[item] += 1;
    })
  
    for (const val in object) {
           if(object[val] == 1) {
              console.log(val);
           }
        }
}
  
const arr = [3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9];

printUniqueElements(arr);

 
 
/*
run:
 
0
5
7
8
 
*/

 



answered May 4, 2020 by avibootz
edited Jul 13, 2025 by avibootz
0 votes
function getUniqueElements(arr) {
    const counts = {};

    // Count occurrences
    arr.forEach(val => {
        counts[val] = (counts[val] || 0) + 1;
    });

    // Collect elements that appear only once
    const unique = [];
    for (const [key, value] of Object.entries(counts)) {
        if (value === 1) {
            unique.push(Number(key));
        }
    }

    return unique;
}

function printUniqueElements(arr) {
    const unique = getUniqueElements(arr);
    
    unique.forEach(val => console.log(val));
}

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

printUniqueElements(arr);

 
 
/*
run:
 
0
5
7
8
 
*/

 



answered Jul 13, 2025 by avibootz
0 votes
const array = [3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9];

const uniqueElements = array.filter((item, index, arr) => 
    arr.indexOf(item) === arr.lastIndexOf(item)
);

console.log(uniqueElements);

 
 
/*
run:
 
[ 5, 7, 8, 0 ]
 
*/

 



answered Jul 13, 2025 by avibootz
...