如何使用jQuery.grep()动态筛选数组

How can I use jQuery.grep() to dynamically filter an array?

本文关键字:动态 筛选 数组 何使用 jQuery grep      更新时间:2023-09-26

我正在尝试过滤一个对象数组以从中删除一些元素。我正在尝试使用jQuery.grep(),但我不知道这是否是最好的工具。

我的对象数组中的每个元素都有一个"type"元素,我需要删除具有特定"type"值的元素。但是这些值是未知的,因为它们将由用户提供。

以下是我遇到的问题:

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

我尝试过获取数组中的所有"type"值,但我不知道该怎么处理。

使用Array.filter过滤掉您不想要或确实想要的内容:

var numbers = [1, 2, 3, 4, 5];
// Filter out `3`
var result = numbers.filter(function (number) {
  return number !== 3;
});
alert(result);

好吧,如果有其他人来找我,@Grundy会让我走上正确的道路。这就是我最终在一些上下文中使用的内容:

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