簡體   English   中英

刪除數組中值的負重復項

[英]Removing negative duplicates of values in an array

說我有一個數組:

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

如何刪除數組中數字的任何否定版本? 因此輸出為:

[-1, 4, 5, 3]

這將濾除數組中所有為負且為正的變量

 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){ return 0; } return 1; }) console.log(arr); 

您可以將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)) 

您需要迭代該數組,然后將所有絕對值都沒有的值添加到第二個數組中:

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

這是根據這個答案改編的, 該答案非常相似。

您可以檢查符號,或者不包括絕對值。

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

使用過濾器

 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; } }) } 

這是一個不使用重復indexOf的版本。 它使用了我以前鏈接的帖子 (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))); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM