bioinform
bioinform

Reputation: 63

Remove duplicates in array separated by double commas in JavaScript

I have an array in JavaScript like this

var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]   

when I alert in JavaScript it gives as below


,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3

But I want like this which is duplicates removed array

var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]

On alert it should give like this

,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3

Upvotes: 2

Views: 1162

Answers (3)

4b0
4b0

Reputation: 22323

You can create your unique function to remove duplicate entry and empty value from array like this.

var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]   
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
  var uniqueResult = [];
  $.each(list, function(i, e) {
    if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
      uniqueResult.push(e);
  });
  return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Bheru Lal Lohar
Bheru Lal Lohar

Reputation: 1060

First Thing your array contains string as a constant that's not going to work.

Secondly, if all of you value are strings you can do it as follows:

var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];

var uniqueArray = data.filter(function(item, pos) {
    return data.indexOf(item) == pos;
})

alert(uniqueArray);

Upvotes: 1

M0nst3R
M0nst3R

Reputation: 5293

Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:

var data [/* ... */];
var unique_data = [];

for(let i = 0; i < data.length; i++) {
    if (data[i] && unique_data.indexOf(data[i]) === -1) {
        unique_data.push(data[i]);
    } 
}

Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().

Upvotes: 1

Related Questions