0

I'm trying to filter an array of objects to remove some elements from it. I'm trying to use jQuery.grep(), but I don't know if that's the best tool for the job.

Every element on my array of objects has a "type" element, and I need to remove the ones with a particular "type" value. But those values are unknown, since they will be provided by the user.

Here's what I'm stuck with:

theNewArray = $.grep(database, function( n ) {
    return ( n.type != /* I don't know what to put here */ );
});

I've tried getting all the "type" values in an array, but I don't know what to do with it.

11
  • 1
    You can use Array.prototype.filter Commented Nov 22, 2015 at 8:54
  • If you want to change original array (like object) you shouldn't use grep because grep doesn't affect original source. Commented Nov 22, 2015 at 8:59
  • You will have to find out what type values are invalid or what type values are valid, so you can === check or !== check against those values. Maybe share some more context? How is the code being used in your app? Commented Nov 22, 2015 at 9:04
  • 1
    Then the question doesn't make any sense. How do you filter something on an unknown criteria? You don't. Commented Nov 22, 2015 at 9:13
  • so, save user input in variable and pass it Commented Nov 22, 2015 at 9:14

2 Answers 2

2

Use Array.filter to filter out what you don't want, or do want:

var numbers = [1, 2, 3, 4, 5];

// Filter out `3`
var result = numbers.filter(function (number) {
  return number !== 3;
});

alert(result);

Sign up to request clarification or add additional context in comments.

1 Comment

but seems OP don't know what pass instead 3
1

Ok, in case any other noob came here after me, @Grundy put me on the right path. This is what I ended up using with some context:

//Example of the original array of objects that I want to filter
var database = [
  {
    firstName:"John",
    lastName:"Doe",
    type:"Man"
  },
  {
    firstName:"Jane",
    lastName:"Doe",
    type:"Woman"
  },
];

//Here I put the user input in an array (simplified)
var filterArray = [];
$("#settings a.uncheck").each(function(){
    filterArray.push($(this).data( "type" ));
});

//And here I remove the objects in the original array that have the "type" values in the user input
filteredDatabase = $.grep(database, function( n ) {
  return ( filterArray.indexOf(n.type) == -1 );
});

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.