0

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]
ItamarG3
  • 4,092
  • 6
  • 31
  • 44
nonono
  • 591
  • 2
  • 8
  • 14

6 Answers6

2

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);
marvel308
  • 10,288
  • 1
  • 21
  • 32
1

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))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

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.

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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;
    }
  })
 }
Ashvin777
  • 1,446
  • 13
  • 19
0

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)));
ASDFGerte
  • 4,695
  • 6
  • 16
  • 33