• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 127
  • Last Modified:

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?
0
brucegust
Asked:
brucegust
  • 3
  • 3
1 Solution
 
GaryCommented:
0
 
brucegustPHP DeveloperAuthor Commented:
Looks good, Gary ,but how do I include the duplicates within the same function?
0
 
GaryCommented:
Uh?
Your question was to get the unique values
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Ray PaseurCommented:
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

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

It has to be in Javascript.
0
 
GaryCommented:
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

0
 
brucegustPHP DeveloperAuthor Commented:
Thanks, Gary!
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now