简体   繁体   中英

Removing zero values from an array of objects

Problem

I'm pushing values from my JavaScript functions and filling an array with objects. what I would like to happen is remove key + Value pairs that are zero.

example of return array

[Object percent: 516 unit: -10.689124404913258
 Object percent: 516  unit: -9.011227255423254
 Object percent: 561  unit: -12.669770888525518
 Object percent: 6516 unit: -15.99180968320506 
 Object percent: 0  unit: 0] 

JavaScript

my_arr = []

  for(var i = my_arr.length - 1; i >= 0; i--) {
    if(array[i] === 0) {
       array.splice(i, 1);
    }
   return my_arr;
}

If you want to remove items from your array which has price and unit you can use this.

 var items = [ { percent: 516, unit: -10.689124404913258 }, { percent: 516, unit: -9.011227255423254 }, { percent: 561, unit: -12.669770888525518 }, { percent: 6516, unit: -15.99180968320506 }, { percent: 0, unit: 0 } ]; items = items.filter(i => i.percent && i.unit); console.log(items); 

BTW the main problem with yours is that you return inside the loop which will stop the loop in the very first turn. I don't even believe that your code works even for a while because using return out side the function scope i kind of error:

Uncaught SyntaxError: Illegal return statement

Just try with:

my_arr.filter(function(element){
  return element.percent && element.unit;
});

If percent and unit properties equal 0 , it will give false result and will be filtered out from the results.

Assuming your source array looks like this...

var sourceArray = [
    { percent: 123, unit: -1 },
    { percent: 456, unit: -2 },
    { percent: 0, unit: 0 },
    { percent: 789, unit: -3 }
];

....then you can get a filtered array using the Array.prototype.filter function:

var filteredArray = sourceArray.filter(function(item) {
    return item.percent || item.unit;
})
// => [
//  { percent: 123, unit: -1 },
//  { percent: 456, unit: -2 },
//  { percent: 789, unit: -3 }
//];

Note that this is checking that both percent and unit are zero before removing the item. If you only need to check one of the values then you can modify the filter function (eg return item.percent if you only want to check percent )

You can just use a filter:

var filtered_array = my_arr.filter(function(el) { return el.percent > 0; });

of course you can include whatever other conditions you like - the filtered array contains all the elements where the callback function returns true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM