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