0

How to display once elements of array ?. For example

var array = ["b","c","c","a","d","e","a","d"]

show => ["a","b","c","d","e"] ?

Any example ?

vivek salve
  • 991
  • 1
  • 9
  • 20

5 Answers5

1

Use the array_unique() function to remove the duplicates and sort - http://php.net/manual/en/function.array-unique.php

Following up with the array_values() function will remove the gaps in the array index - http://php.net/manual/en/function.array-values.php

// initialize array
var $array = array("b","c","c","a","d","e","a","d");
// remove duplicates and sort by string value
$array = array_unique($array, SORT_STRING);
// reindex array (numeric index will have gaps where the duplicates where removed)
$array = array_values($array);
// show results
print_r($array);

In Javascript/jQuery you can use the unique() and sort() methods

// initialize array
var array = ["b","c","c","a","d","e","a","d"];
// remove duplicate values
array.unique();
// sort remaining items
array.sort();

If you are sorting numbers in Javascript, you would need to pass a function, as the array is sorted lexicographically be default

array.sort(function(a,b){return a - b;});
doublesharp
  • 26,888
  • 6
  • 52
  • 73
1

PHP

array_unique($array, SORT_STRING)

jQuery

array.unique()
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
0

in php you should use array_unique and sort for sorting array

$arr = array("b","c","c","a","d","e","a","d");
sort($arr);
print_r(array_unique($arr));
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
0
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

source:stack overflow

Community
  • 1
  • 1
Arun Killu
  • 13,581
  • 5
  • 34
  • 61
0

qustion asked:- How to display once elements of array ?. For example

var array = ["b","c","c","a","d","e","a","d"]

show => ["a","b","c","d","e"] ?

Any example ?


answer:- $arr = array("b","c","a","d","e","a","d");

$unique = array_unique($arr);//remove all duplicate values

sort($unique);//sort is done here

echo ""; print_r($unique );//shows show => ["a","b","c","d","e"]

Ankur Saxena
  • 629
  • 3
  • 13
  • 26