how to set only unique values in array in javascript code example

Example 1: javascript find unique values in array

// usage example:
var myArray = ['a', 1, 'a', 2, '1'];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i); 

// unique is ['a', 1, 2, '1']

Example 2: javascript remove duplicates from array

function toUniqueArray(a){
    var newArr = [];
    for (var i = 0; i < a.length; i++) {
        if (newArr.indexOf(a[i]) === -1) {
            newArr.push(a[i]);
        }
    }
  return newArr;
}
var colors = ["red","red","green","green","green"];
var colorsUnique=toUniqueArray(colors); // ["red","green"]

Example 3: unique numbers in array

import java.util.ArrayList;

public class UniqueNumbersInArray {

    public static void main(String[] args) {


    int arr[] = { 4,5,5,4,5,6,5,8,4,7};

        ArrayList<Integer> uniqueArr = new ArrayList<Integer>();
        for (int i = 0; i < arr.length; i++) {

            int k = 0;
            if (!uniqueArr.contains(arr[i])){
                uniqueArr.add(arr[i]);
                k++;

                for (int j = i; j < args.length ; j++) {
                    if (arr[i]==arr[j]){
                        k++;
                    }
                }

                System.out.println(arr[i]);
                System.out.println(k);
            }

        }
    }
}

Tags:

Java Example