0

This question may look quite similar to [ ][1]Remove Duplicates from JavaScript Array, but it's really different: I need to find equal elements in array and delete them all, for example,

var arr1 = ["andesite", "grass", "dirt", "pink wool", "dead shrub", "grass"];

the result must be:

var arr1 = ["andesite", "dirt", "pink wool", "dead shrub"];

What I want is to find out that "grass" goes there twice, and exclude both from the array. I've tried something like

function inArray(arr){
var index = [];
var count = arr.length;
for(var i=0;i<count;i++){

    if(arr[i] in index){

        arr.splice([i],1);          

        }else{
            index1.push(arr[i]);
        }
    }
return arr;

} but it removes only the second duplicating element when comparing it with the first one.

Thank you in advance for any responce. This is an educating task for me, so, I will highly appreciate explanations how it works.

Community
  • 1
  • 1
Max
  • 3
  • 5
  • here is one way of doing it: 1) make a pass on the array and find out which items appear more than once -> save them somewhere distinctly. 2) make a second pass on the array and remove all those items you saved before – Banana Nov 09 '15 at 19:28

1 Answers1

3

Okay, so the first step is, of course, to identify which elements you want to remove. Step two will be to remove them.

Identifying duplicates is easy enough and can be done in a number of ways. Here's how I'd do it:

var counts = {};
for( var i=0, l=arr.length; i<l; i++) {
    counts[arr[i]] = (counts[arr[i]] || 0) + 1;
}

Any key in counts that has a value greater than 1 will now need removing. That, too, is simple:

var result = arr.filter(function(item) {
    return counts[item] <= 1;
});

And... done! This will filter out any items where counts[item] <= 1 fails, effectively removing any item that appeared twice or more. It's that simple ^^

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592