1

i have two arrays, balances and commits

balances =  [
{name: 'vacation', value: ''21},
{name: 'account', value: '200'},
{name: 'order', value: '15'},
]

commits = [
{balanceName: 'vacation', paramName: 'number of days'},
{balanceName: 'order', paramName: 'number of items'}
]

i want to remove form balances what is not in commits, in this example i want to remove account value from balances cause it is not in any of the balanceName of commits how can i do this by underscore or any other library

scully
  • 961
  • 2
  • 8
  • 13
  • You can refer this link https://stackoverflow.com/questions/10110510/underscore-js-determine-if-all-values-in-an-array-of-arrays-match – Ashish Patel Jul 26 '17 at 11:48
  • Possible duplicate of [How to filter array when object key value is in array](https://stackoverflow.com/questions/35817565/how-to-filter-array-when-object-key-value-is-in-array) – Aryeh Katz Jul 26 '17 at 12:02

2 Answers2

2

You can do that using undescore.js like this:

var balances =  [
{name: 'vacation', value: '21'},
{name: 'account', value: '200'},
{name: 'order', value: '15'}
]

var commits = [
{balanceName: 'vacation', paramName: 'number of days'},
{balanceName: 'order', paramName: 'number of items'}
]
balances2=
_.filter(balances,(b)=>commits.map(c=>c.balanceName).indexOf(b.name)>-1);

console.log("using shorter syntax");
console.log(balances)

//OR
balances=
    _.filter(balances,function(b){return commits.map(function(c){return c.balanceName}).indexOf(b.name)>-1});
    
    console.log("ES5 syntax");
console.log(balances2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

_.filter will return all entries that match criteria. _.find, for instance will return only first entry. I also used _.map which converts array with multiple properties to some other array by using transform function (in my case c=>c.balanceName).

Vlado Pandžić
  • 4,879
  • 8
  • 44
  • 75
-1

No need for a library for this.

function contains(commits, name)
{
    commits.some(function(x) { return x.balanceName === name});
}

for(blance in balances) {
    if (contains(commits, balance.name){
        // Remove balance
    }
}