2017-08-13 40 views
0

說我有一個數組:刪除值的負重複陣列中的

var arr = [-1, -5, 4, 5, 3]; 

我如何會刪除陣列中的一些任何負面的版本?因此,輸出將是:

[-1, 4, 5, 3] 
+0

[拔下JavaScript數組複製(https://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array) – ASDFGerte

+0

有你自己嘗試新鮮事物? – ItamarG3

+0

@ASDFGerte不,因爲這些不重複。它們的絕對值是重複的。 – ItamarG3

回答

2

這將過濾掉哪些是消極的所有變量和陣列中具有積極作用

var arr = [-1, -5, 4, 5, 3, -5]; 
 

 
arr = arr.filter(function(a, b){ 
 
    if(a < 0 && arr.indexOf(-1*a) > -1){ 
 
    return 0; 
 
    } 
 
    if(a < 0 && arr.indexOf(a) != b){ 
 
    \t return 0; 
 
    } 
 
    return 1; 
 
}) 
 

 
console.log(arr);

+0

完美,謝謝! –

0

您需要遍歷數組,並添加所有那些沒有他們的絕對值已經在第二個陣列:

var noDups = []; 
$.each(arr, function(i, v){ 
    if($.inArray(abs(v), noDups) === -1 || $.inArray(v,noDups)===-1){ 
     noDups.push(v); 
    } 
}); 

這是改編自this answer,這非常相似。

1

您可以使用filter()Math.abs()

var arr1 = [-1, -5, 5, 4, 3]; 
 
var arr2 = [-1, -5, -5, 4, 3]; 
 

 

 
function customFilter(arr) { 
 
    return arr.filter(function(e) { 
 
    if (e > 0) return true; 
 
    else { 
 
     var abs = Math.abs(e) 
 
     if (arr.indexOf(abs) != -1) return false; 
 
     else return !this[e] ? this[e] = 1 : false; 
 
    } 
 
    }, {}) 
 
} 
 

 
console.log(customFilter(arr1)) 
 
console.log(customFilter(arr2))

0

你可以檢查標誌,或者如果不包括絕對值。

var array = [-1, -5, 4, 5, 3], 
 
    result = array.filter((a, _, aa) => a >= 0 || !aa.includes(Math.abs(a))); 
 
    
 
console.log(result);

0

使用過濾器

var arr = [-1, -5, 4, 5, 3, 4, -6, 4, 6]; 
 

 
console.log(removeNegativesCommon(arr)); 
 

 
function removeNegativesCommon(arr){ 
 
    return arr.filter((el) => { 
 
    if(el < 0 && arr.indexOf(Math.abs(el)) != -1){ 
 
     return false; 
 
    } else { 
 
     return el; 
 
    } 
 
    }) 
 
}

0

這裏是不使用重複indexOf一個版本。它使用來自my previously linked post(uniq函數)的解決方案,以及之前已經包含爲正數的負數消除。

var arr = [-1, -5, 4, 5, 3]; 
 

 
function uniq(a) { 
 
    var seen = {}; 
 
    return a.filter(function(item) { 
 
     return seen.hasOwnProperty(item) ? false : (seen[item] = true); 
 
    }); 
 
} 
 

 
function preRemoveNegatives(a) { 
 
    let table = {}; 
 
    a.filter(e => e >= 0).forEach(e => table[e] = true); 
 
    return a.filter(e => e >= 0 || !table[-e]); 
 
} 
 

 
console.log(uniq(preRemoveNegatives(arr)));