1

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?

4 Answers 4

1

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" ) 
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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

Comments

0

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, {}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.