We help IT Professionals succeed at work.

I've got to find the unique values in an array as well as the duplicates using Javascript. How?

Bruce Gust
Bruce Gust asked
on
154 Views
Last Modified: 2014-08-03
Here's my dilemma:

I have to return distinct values from a list including duplicates.

So if I've got a list like this: "1 3 5 3 7 3 1 1 5"

...I've got to return this:  "1 3 5 7"

How?
Comment
Watch Question

CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
Bruce GustPHP Developer

Author

Commented:
Looks good, Gary ,but how do I include the duplicates within the same function?
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
Uh?
Your question was to get the unique values
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Are you looking for an answer in PHP or in JavaScript?  I can add the PHP Zone if that's appropriate.

Unique: http://php.net/manual/en/function.array-unique.php
Not unique:

<?php // demo/array_not_unique.php
error_reporting(E_ALL);
echo "<pre>";

// A FUNCTION TO FIND REPLICATED VALUES IN AN ARRAY
function array_not_unique($raw)
{
    // MAN PAGE: http://php.net/manual/en/function.array-count-values.php
    $new = array_count_values($raw);
    foreach ($new as $key => $val)
    {
        if ($val < 2) unset($new[$key]);
    }
    return $new;
}

// SOME TEST DATA
$raw_array   = array();
$raw_array[] = 'abc@xyz.com';
$raw_array[] = 'def@xyz.com';
$raw_array[] = 'ghi@xyz.com';
$raw_array[] = 'jkl@xyz.com';
$raw_array[] = 'mno@xyz.com';
$raw_array[] = 'pqr@xyz.com';
$raw_array[] = 'stu@xyz.com';

// SOME DUPLICATES
$raw_array[] = 'abc@xyz.com';
$raw_array[] = 'jkl@xyz.com';
$raw_array[] = 'abc@xyz.com';
$raw_array[] = 'def@xyz.com';


// SHOW THE FUNCTION AT WORK
$common = array_not_unique($raw_array);

// SHOW THE WORK PRODUCT
foreach ($common as $x => $n)
{
    echo PHP_EOL . "THE VALUE $x APPEARED $n TIMES";
}

Open in new window

Bruce GustPHP Developer

Author

Commented:
No, I need this in Javascript. Didn't even look at the original reply until just now.

It has to be in Javascript.
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Bruce GustPHP Developer

Author

Commented:
Thanks, Gary!
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.