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

Bruce Gust
Bruce Gust used Ask the Experts™
on
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

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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?
Expert of the Year 2014
Top Expert 2014

Commented:
Uh?
Your question was to get the unique values
Should you be charging more for IT Services?

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Most Valuable Expert 2011
Top Expert 2016

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.
Expert of the Year 2014
Top Expert 2014
Commented:
var arrayUnique = function(a) {
    return a.reduce(function(i, e) {
        if (i.indexOf(e) < 0) i.push(e);
        return i;
    },[]);
};

myArray="1 3 5 3 7 3 1 1 5".split(" ")

console.log(arrayUnique(myArray))

Open in new window

Bruce GustPHP Developer

Author

Commented:
Thanks, Gary!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial