array unique values 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: array_unique

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Example 3: find unique values between multiple array

var array3 = array1.filter(function(obj) { return array2.indexOf(obj) == -1; });

Example 4: 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 5: get only unique values from array javascript

arr = [2, 2, 2, 1, 3, 3, 3,3, 4, 5];
arr = arr.sort().filter((item,i)=>!(arr[i] == arr[i+1] || arr[i-1]==arr[i]));
// this will remove all item which are repeating more then one
console.log(arr);
// [1, 4, 5]

Example 6: how to create an array with unique values

import java.util.Random;

public class GenRandArray {
    //Recommend reseeding within methods
    static Random rand = new Random();

    public static void fillInt( int[] fillArray ) {
        //seeds the random for a new random each method call
        rand.setSeed(System.currentTimeMillis());
		
        for(int i = 0; i < fillArray.length; i++)
        {
            fillArray[i]= rand.nextInt();
            
          	/* for loop to check to make sure that none of the previous
               numbers added are the same as the one just added. */
            for (int j = 0; j < i; j++)
            {
              	/* if so we need to redo the last random number by
              	   moving i back one index to be re-set */
                if (fillArray[i] == fillArray[j])
                {
                    i--;
                }
            }
        }
    }
}

Tags:

Misc Example