VijayVishnu
VijayVishnu

Reputation: 537

Filter matched items in an array of string with another (key,value) objects in angularjs

I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".

String Array:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]

(key,value) Objects:

var obj = {"viki-1100":6,"mark-2100":2}

To return only the non matched keys from stringArr,So desired output:

var result = ["vijay-1110","ram-2110"]

I haven tried the below code which doesnot return the desired output?

var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
    return stringArr;
}
else{
    _.each(stringArr,function(input,index){
        Object.keys(obj).forEach(function(key) {
            if(input === key){
                stringArr.splice[index,1];
            }
        });
    });
    return stringArr;
}

this wont filter the stringArr, It always return all the results in stringArr?

Upvotes: 1

Views: 54

Answers (4)

gurvinder372
gurvinder372

Reputation: 68373

Try

stringArr.filter( s => typeof obj[s] != "undefined" ) 

Edit

I realized that OP is looking for the opposite of my answer, so simply replaced != with ==

stringArr.filter( s => typeof obj[s] == "undefined" ) 

Upvotes: 1

Faly
Faly

Reputation: 13346

The code below works and manage the case where obj is an empty object. Object.keys(...).length is here to check if obj is an empty object or not

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"];
var obj = {"viki-1100":6,"mark-2100":2};
var filterFunction = function(stringArr,obj){
    return stringArr.filter(str => Object.keys(obj).length === 0 || obj[str] );
}

console.log(filterFunction(stringArr, obj));
console.log(filterFunction(stringArr, {}));

Upvotes: 0

Mamun
Mamun

Reputation: 68933

Try the following way:

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]
var obj = {"viki-1100":6,"mark-2100":2}

var result = stringArr.filter(function(item){
  return !(item in obj)
});
console.log(result)

Upvotes: 0

Hassan Imam
Hassan Imam

Reputation: 22524

You can use in to check if a key exist inside an object. Use array#filter to iterate through your array and for each value return the non-existent value.

var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"];
var obj = {"viki-1100":6,"mark-2100":2};
var result = stringArr.filter(name => !(name in obj));
console.log(result);

Upvotes: 0

Related Questions