2016-08-30 2 views
0

Angenommen, ich habe das Array [1,2,3,5,2,1,4]. Wie bekomme ich JS Rückkehr [3,4,5]?Rückgabewerte, die nur einmal vorkommen (JavaScript)

Ich habe mir hier andere Fragen angeschaut, aber es geht darum, die Kopien einer Nummer zu löschen, die mehr als einmal erscheint, nicht sowohl das Original als auch die Kopien.

Danke!

+0

http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array –

Antwort

2

Verwenden Sie Array#filter Methode zweimal.

var data = [1, 2, 3, 5, 2, 1, 4]; 
 

 
// iterate over elements and filter 
 
var res = data.filter(function(v) { 
 
    // get the count of the current element in array 
 
    // and filter based on the count 
 
    return data.filter(function(v1) { 
 
    // compare with current element 
 
    return v1 == v; 
 
    // check length 
 
    }).length == 1; 
 
}); 
 

 
console.log(res);


Oder eine andere Art und Weise mit Array#indexOf und Array#lastIndexOf Methoden.

var data = [1, 2, 3, 5, 2, 1, 4]; 
 

 
// iterate over the array element and filter out 
 
var res = data.filter(function(v) { 
 
    // filter out only elements where both last 
 
    // index and first index are the same. 
 
    return data.indexOf(v) == data.lastIndexOf(v); 
 
}); 
 

 
console.log(res);

+1

Erklärung arrayfilter könnte hilfreich sein zu –

+0

OP hat nur getaggt Javascript und Filter in jquery Funktion. – Mairaj

+0

@Leopard: Bist du sicher? :) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter –

1

Sie können auch .slice().sort()

var x = [1,2,3,5,2,1,4]; 
 
var y = x.slice().sort(); // the value of Y is sorted value X 
 

 
var newArr = []; // define new Array 
 

 
for(var i = 0; i<y.length; i++){ // Loop through array y 
 
    if(y[i] != y[i+1]){ //check if value is single 
 
    newArr.push(y[i]); // then push it to new Array 
 
    }else{ 
 
    i++; // else skip to next value which is same as y[i] 
 
    } 
 
} 
 

 

 
console.log(newArr);

verwenden Wenn Sie newArr überprüfen es Wert hat:

0
var arr = [1,2,3,5,2,1,4] 
var sorted_arr = arr.slice().sort(); // You can define the comparing function here. 
var nonduplicates = []; 
var duplicates=[]; 
for (var i = 0; i < arr.length; i++) { 
    if (sorted_arr[i + 1] == sorted_arr[i]) { 
     duplicates.push(sorted_arr[i]); 
    }else{ 
     if(!duplicates.includes(sorted_arr[i])){ 
     nonduplicates.push(sorted_arr[i]); 
     } 
    } 
} 

alert("Non duplicate elements >>"+ nonduplicates); 
alert("Duplicate elements >>"+duplicates); 
Verwandte Themen