[英]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 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.