scully
scully

Reputation: 981

underscorejs how to compare between two arrays?

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

Upvotes: 1

Views: 1054

Answers (2)

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
    }
}

Upvotes: -1

Vlado Pandžić
Vlado Pandžić

Reputation: 5048

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).

Upvotes: 2

Related Questions