3

Possible Duplicate:
Easiest way to find duplicate values in a JavaScript array
Javascript array sort and unique

I have the following array

var output = new array(7);
  output[0]="Rose";
  output[1]="India";
  output[2]="Technologies";
  output[3]="Rose";
  output[4]="Ltd";
  output[5]="India";
  output[6]="Rose";

how can i remove the duplicate elements in above array.Is there any methods to do it?

Community
  • 1
  • 1
vishnu
  • 869
  • 1
  • 16
  • 25
  • What have you tried? There is no function natively available, but it isn't very hard to write yourself. – Halcyon Mar 17 '12 at 15:57
  • This is been asked already.. http://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript And the solution there is really clever and good.. – Prasanna Mar 17 '12 at 16:02
  • i tried for (var i = 0; i < output.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } – vishnu Mar 17 '12 at 16:07

4 Answers4

9

You can write a function like this

function eliminateDuplicates(arr) {
var i,
  len=arr.length,
  out=[],
  obj={};

 for (i=0;i<len;i++) {
 obj[arr[i]]=0;
 }
 for (i in obj) {
 out.push(i);
 }
 return out;
}`

Check this here

asitmoharna
  • 1,484
  • 11
  • 15
3

Maybe more complex than you need but:

function array_unique (inputArr) {
    // Removes duplicate values from array  
    var key = '',
        tmp_arr2 = {},
        val = '';

    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if (haystack.hasOwnProperty(fkey)) {
                if ((haystack[fkey] + '') === (needle + '')) {
                    return fkey;
                }
            }
        }
        return false;
    };

    for (key in inputArr) {
        if (inputArr.hasOwnProperty(key)) {
            val = inputArr[key];
            if (false === __array_search(val, tmp_arr2)) {
                tmp_arr2[key] = val;
            }
        }
    }

    return tmp_arr2;
}

Code taken from: http://phpjs.org/functions/array_unique:346

nathanjosiah
  • 4,441
  • 4
  • 35
  • 47
  • 1
    Don't you think that might a *bit* overcomplicated for the OP? He's obviously just getting into Javascript. Then again, he could just copy-paste and let the magic function do its trick, but that's not very helpful or in the spirit of good learning... – Elliot Bonneville Mar 17 '12 at 16:02
  • It's a complex thing to be doing just if you are just starting out. I assumed he needed a copy-paste solution. – nathanjosiah Mar 17 '12 at 16:03
1

First of all, you'll want to use the array literal (var output = []) to declare your array. Second, you'll want to loop through your array and store all the values in a second array. If any value in the first array matches a value in the second array, delete it and continue looping.

Your code would look like this:

var output = [
    "Rose",
    "India",
    "Technologies",
    "Rose",
    "Ltd",
    "India",
    "Rose"
]

var doubledOutput = [];

for(var i = 0; i < output.length; i++) {
    var valueIsInArray = false;

    for(var j = 0; j < doubledOutput.length; j++) {
        if(doubledOutput[j] == output[i]) {
            valueIsInArray = true;
        }
    }

    if(valueIsInArray) {
        output.splice(i--, 1);
    } else {
        doubledOutput.push(output[i]);
    }
}

Please note, the above code is untested and may contain errors.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • Can I ask the reason for the unexplained downvote? It's just a simple, readable, and easy way of finding duplicate values for a beginner in Javascript who obviously doesn't need a complicated and overworked solution. – Elliot Bonneville Mar 17 '12 at 16:01
  • I didn't downvote, but you're both incrementing `i` *and* deleting items. You'll be missing elements that way, unless you decrement `i` a well when splicing an element. – pimvdb Mar 17 '12 at 16:05
  • Oops, yeah, I should have used a reverse loop. My bad, thanks for the catch. – Elliot Bonneville Mar 17 '12 at 16:06
  • In fact I think you meant to change `valueIsInArray` to `true` and to actually populate `doubledOutput`... – pimvdb Mar 17 '12 at 16:08
  • Guilty as charged. I wrote up the code really quickly so as to get the answer in before somebody else... doesn't help that I haven't had my coffee yet either. Fixing all counts. :) – Elliot Bonneville Mar 17 '12 at 16:10
  • A little friendly advice... before you criticize another answer for not being *"in the spirit of good learning"*, make sure your own is correct. I don't think a *"Please note, the above code is untested and may contain errors."* warning is helpful to a beginner. –  Mar 17 '12 at 16:15
  • ...I assume you meant to do `var i = output.length - 1` so you don't start outside the length of the array. –  Mar 17 '12 at 16:16
  • ...also, an Array doesn't have an `.append()` method, and nothing will be added to the `doubledOutput` Array. –  Mar 17 '12 at 16:19
  • http://i2.kym-cdn.com/entries/icons/original/000/000/554/facepalm.jpg You know what, next time I'm just going to test my code first. – Elliot Bonneville Mar 17 '12 at 16:38
1

You can remove dups from an array by using a temporary hash table (using a javascript object) to keep track of which images you've already seen in the array. This works for array values that can be uniquely represented as a string (strings or numbers mostly), but not for objects.

function removeDups(array) {
    var index = {};
    // traverse array from end to start 
    // so removing the current item from the array
    // doesn't mess up the traversal
    for (var i = array.length - 1; i >= 0; i--) {
        if (array[i] in index) {
            // remove this item
            array.splice(i, 1);
        } else {
            // add this value to index
            index[array[i]] = true;
        }
    }
}

Here's a working example: http://jsfiddle.net/jfriend00/sVT7g/

For sizable arrays, using an object as a temporary index will be many times faster than a linear search of the array.

jfriend00
  • 683,504
  • 96
  • 985
  • 979