Say I have an array:
var arr = [-1, -5, 4, 5, 3];
How would I remove any negative versions of a number in the array? So the output would be:
[-1, 4, 5, 3]
Say I have an array:
var arr = [-1, -5, 4, 5, 3];
How would I remove any negative versions of a number in the array? So the output would be:
[-1, 4, 5, 3]
This would filter out all variables which are negative and have a positive part in the array
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);
You can use filter()
with 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))
You need to iterate the array, and add all those that don't have their absolue value already in the second array:
var noDups = [];
$.each(arr, function(i, v){
if($.inArray(abs(v), noDups) === -1 || $.inArray(v,noDups)===-1){
noDups.push(v);
}
});
This was adapted from this answer, which is very similar.
You could check the sign or if the absolute value is not included.
var array = [-1, -5, 4, 5, 3],
result = array.filter((a, _, aa) => a >= 0 || !aa.includes(Math.abs(a)));
console.log(result);
Use Filter
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;
}
})
}
Here is a version that does not use repeated indexOf
. It uses a solution from my previously linked post (uniq function) along with a prior removal of negatives that already are included as positives.
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)));