How to get the unique values of an array in TypeScript

1 Answer

0 votes
function arrayUnique(arr: number[]): number[] {
    const result: number[] = [];
    
    arr.forEach(val => {
        if (!result.includes(val)) {
            result.push(val);
        }
    });
    
    return result;
}

const arr: number[] = [1, 2, 1, 1, 3, 3, 4, 4, 5, 5, 5, 5, 6, 7, 7, 8];
const result: number[] = arrayUnique(arr);

result.forEach(val => console.log(val));


  
  
/*
run:
  
1 
2 
3 
4 
5 
6 
7 
8 
  
*/

 



answered Feb 18, 2025 by avibootz
...