隐藏

JS filter()模糊查询,过滤

发布:2024/12/12 23:07:59作者:管理员 来源:本站 浏览次数:104

   filter() 方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。


   示例1:过滤出非0并且有效id


const arr = [

   { id: 15 },

   { id: -1 },

   { id: 0 },

   { id: 3 },

   { id: 12.2 },

   {},

   { id: null },

   { id: NaN },

   { id: "undefined" },

];


const newArr = arr.filter((item) => {

   return Number.isFinite(item.id) && item.id !== 0

})


console.log(newArr)   //  [{id: 15},{id: -1},{id: 3},{id: 12.2}]



运行


   示例2:根据搜索条件模糊(查询)筛选数组项


const fruits = ["apple", "banana", "grapes", "mango", "orange"];


// arr:需要过滤的数组, searchKey:过滤关键字

function filterItems(arr, searchKey) {

    return arr.filter((el) => el.toLowerCase().includes(searchKey.toLowerCase()))

}

console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']

console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']


var list1 = [{ "ID": "1", Value: "1" }, { "ID": "2", Value: "1" }];
var list2 = [{ "ID": "1", Value: "1" }];
for (i = 0; i < list1.length; i++) {
    var arr = list2.map(function (o) { return o.ID; });

    if ((arr.indexOf(list1[i].ID) > -1)) {
        //存在
        console.log('存在' + list1[i].ID);
    }
    else {
        //不存在
        console.log('不存在' + list1[i].ID);
    }
}
console.log('丰');

let users = [
    { id: 1, name: 'John', age: 25 },
    { id: 2, name: 'Jane', age: 22 },
    { id: 3, name: 'John', age: 30 },
    { id: 4, name: 'Doe', age: 23 }
];

// 查询名字为"John"的用户
let johns = users.filter(user => user.name === 'John');

console.log(johns);

function fuzzySearch(list, query) {
    return list.filter(item =>
        Object.values(item).some(value =>
            value.toString().includes(query)
        )
    );
}

// 示例使用
const items = [
    { name: 'Apple', category: 'Fruit' },
    { name: 'Banana', category: 'Fruit' },
    { name: 'Carrot', category: 'Vegetable' },
    { name: 'Chicken', category: 'Meat' }
];

const searchQuery = 'r'; // 模糊查询词
const results = fuzzySearch(items, searchQuery);

console.log(results); // 将输出包含'na'的所有对象
let ss = items.filter((e) => e.name == 'Apple');
console.log(ss);

const fruits = ["apple", "banana", "grapes", "mango", "orange"];

// arr:需要过滤的数组, searchKey:过滤关键字
function filterItems(arr, searchKey) {
    return arr.filter((el) => el.toLowerCase().includes(searchKey.toLowerCase()))
}
console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
// arr:需要过滤的数组, searchKey:过滤关键字
function filterItemsJson(arr, searchKey) {
    return arr.filter((el) => el.toLowerCase().includes(searchKey.toLowerCase()))
}

ss = items.filter((e) => e.name.includes('C'));
console.log(ss);