Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

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

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?
Avatar of Gary
Gary
Flag of Ireland image

Avatar of Bruce Gust

ASKER

Looks good, Gary ,but how do I include the duplicates within the same function?
Uh?
Your question was to get the unique values
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

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

It has to be in Javascript.
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks, Gary!