JS implements array filtering from simple to multi-condition filtering

JS implements array filtering from simple to multi-condition filtering

When I was working at my previous company, there was a requirement to complete the filtering function on the front end, get all the data at once, and then filter according to the conditions. Normally, filtering is done through the backend interface. When the amount of data is not large, some people may encounter front-end filtering. I wrote this article to share with you. If you have any questions, please point them out so that we can learn from each other.

In general, for single-condition filtering, the filter method of the array can meet the needs. This article focuses on compound filtering under multiple conditions and lists several related knowledge points.

Here are a lot of 🌰🌰🌰🌰

// This is the filtered array in the example var aim = [
    {name:'Anne', age: 23, gender:'female'},
    {name:'Leila', age: 16, gender:'female'},
    {name:'Jay', age: 19, gender:'male'},
    {name:'Mark', age: 40, gender:'male'}
]

Single condition single data filtering

Filter by a single name and use the filter method to determine whether the name is the target name.

// Filter by single name function filterByName(aim, name) {
    return aim.filter(item => item.name == name)
}
// Input aim 'Leila' Expected output: [{name:'Leila', age: 16, gender:'female'}]
console.log(filterByName(aim,'leila'))

Single condition multiple data filtering

To filter by multiple names, we use a for loop to traverse the target array, and then use the find method to find and push it into the result array. The find method can get the desired result even if there are duplicate names. The for loop can be replaced by some array traversal methods, the code can be simplified, and the example is just to express the general idea.

// Filter by multiple names function filterByName1(aim, nameArr) {
    let result = []
    for(let i = 0; i < nameArr.length; i++) {
        result.push(aim.find(item => item.name = nameArr[i]))
    }
    return result
}
// Input aim ['Anne','Jay'] 
//Expected output is [{name:'Anne', age: 23, gender:'female'},{name:'Jay', age: 19, gender:'male'}]
console.log(filterByName1(aim,['Leila','Jay']))
// After BUG improvement

Multiple conditional data filtering

To filter by a single name or a single age, use the filter method to determine whether the conditions are in an OR relationship.

// Filter by name or age function filterByName2(aim, name, age) {
    return aim.filter(item => item.name == name || item.age == age)
}
console.log(filterByName2(aim,'Leila',19))

Multiple conditions and multiple data filtering

I initially tried using a clumsy double for loop, but it was slow and didn't produce the desired effect. The specific mental journey is too far away, so I will briefly introduce the following screening algorithm.
The first step is to put all the filtering conditions into an object, and use the keys method of the object object to get the name of the filtering condition and which condition needs to be filtered, is it name? age? gender?
Then use the filter method to filter the target data, as follows⬇️
Filter by name and age

//Filter multiple elements based on name and age export function multiFilter(array, filters) {
  const filterKeys = Object.keys(filters)
  // filters all elements passing the criteria
  return array.filter((item) => {
    // dynamically validate all filter criteria
    return filterKeys.every(key => {
        //ignore when the filter is empty Anne
      if (!filters[key].length) return true
      return !!~filters[key].indexOf(item[key])
    })
  })
}
/*
 * This code is not original to me. If you are interested, you can go to the original author and give a thumbs up* The author is: @author https://gist.github.com/jherax
 * I only added one line in this code to solve the problem that the overall filter fails when some filter conditions are cleared*/

var filters = {
    name:['Leila', 'Jay'],
    age:[]
}
/* result:
 * [{name: "Leila", age: 16, gender: "female"},
 * {name: "Jay", age: 19, gender: "male"}]
 */

For example, here, we determine whether the name value of each data is in the filters.name array. If so, true is returned. If filters.age is an empty array, true is returned directly. The empty array simulates the situation where the age condition is cleared, and we can still get the correct filtered data.

Knowledge point 1: Object.key() gets array index or object attribute

var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); 
// ["0", "1", "2"]


var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); 
// ["0", "1", "2"]


var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); 
// ["2", "7", "100"] Guess why?

Knowledge point 2: falsy in js

falsy : 0 , false , "", null , undefined , NaN

In the judgment statement, only the above 6 cases will be false, and the rest are true

var a;
if(a!=null&&typeof(a)!=undefined&&a!=''){
    //code that will only be executed if a has content}

if(!!a){
    //aCode that is executed only if there is content...  
}

Knowledge point 3: The difference between Array.every and Array.some

My understanding is that when traversing an array:

  • The condition of Array.every is an "and" relationship. If all conditions are true, it returns true. If one condition is false, it returns false.
  • The condition of Array.some is an "or" relationship. It returns true if one of the conditions is true, and returns false if all conditions are false.

Here is an example 🌰

// Check if each name is Anne?
let dataEvery = aim.every(item => item.name === 'Anne') // false
let dataEvery = aim.some(item => item.name === 'Anne') // true

// Check if each name is a string?
let dataEvery = aim.every(item => typeof item.name === 'string') // true
let dataEvery = aim.some(item => typeof item.name === 'string') // true

Knowledge point 4: Deep copy and shallow copy of array

I have recently participated in some front-end interviews, and deep copy and shallow copy are one of my favorite questions. One question examines data types, array operations, recursive algorithms, etc.

Because arrays are reference types in js, when they are simply copied, their reference relationships are copied. When filtering the acquired data, I do not want to affect the original data, so I need to use "deep copy" to obtain data that is completely identical to the original data structure and independent of each other, rather than just copying its reference relationship.

// I usually use this method. If the project is large, it is not recommended. let obj1 = JSON.parse(JSON.stringify(obj))

//deepclone
function deepClone(o1, o2) {
    for (let k in o2) {
        if (typeof o2[k] === 'object') {
            o1[k] = {};
            deepClone(o1[k], o2[k]);
        } else {
            o1[k] = o2[k];
        }
    }
}

Think about it: Optimizing recursive algorithms

This knowledge point has little to do with this article. 😄 Sorry for the previous misleading.

I saw this when I was reading the front-end interview guide in the Nuggets booklet. When they talked about algorithms, they mentioned the optimization of recursive algorithms. I was amazed when I first saw it, but I haven't used it in the project yet. If you are interested, you can try it. This is the sum of the Fibonacci sequence. You can type it in your browser to see the difference between the number of operations without caching and with caching.

let count = 0;
function fn(n) {
    let cache = {};
    function _fn(n) {
        if (cache[n]) {
            return cache[n];
        }
        count++;
        if (n == 1 || n == 2) {
            return 1;
        }
        let prev = _fn(n - 1);
        cache[n - 1] = prev;
        let next = _fn(n - 2);
        cache[n - 2] = next;
        return prev + next;
    }
    return _fn(n);
}

let count2 = 0;
function fn2(n) {
    count2++;
    if (n == 1 || n == 2) {
        return 1;
    }
    return fn2(n - 1) + fn2(n - 2);
}

This concludes this article about implementing array filtering with JS from simple to multi-condition filtering. For more relevant JS array filtering content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • An article to help you learn more about JavaScript arrays
  • Detailed explanation of several methods of deduplication in Javascript array
  • Detailed explanation of built-in methods of javascript array
  • Commonly used JavaScript array methods
  • JavaScript Array Detailed Summary
  • JavaScript commonly used array deduplication actual combat source code
  • How to monitor array changes in JavaScript
  • Examples and comparison of 3 methods for deduplication of JS object arrays
  • JavaScript array reduce() method syntax and example analysis
  • Implement 24+ array methods in JavaScript by hand

<<:  MySQL 5.5.56 installation-free version configuration method

>>:  When backing up files in Centos7, add the backup date to the backup file

Recommend

About VUE's compilation scope and slot scope slot issues

What are slots? The slot directive is v-slot, whi...

Implementation of navigation bar and drop-down menu in CSS

1. CSS Navigation Bar (1) Function of the navigat...

How to avoid the trap of URL time zone in MySQL

Preface Recently, when using MySQL 6.0.x or highe...

Ubuntu 20.04 Chinese input method installation steps

This article installs Google Input Method. In fac...

Example of viewing and modifying MySQL transaction isolation level

Check the transaction isolation level In MySQL, y...

View the number of files in each subfolder of a specified folder in Linux

count script #!/bin/sh numOfArgs=$# if [ $numOfAr...

How to use js to determine whether a file is utf-8 encoded

Conventional solution Use FileReader to read the ...

Build a high-availability MySQL cluster with dual VIP

Table of contents 1. Project Description: 2. Proj...

JavaScript Shorthand Tips

Table of contents 1. Merge arrays 2. Merge arrays...

Webpack builds scaffolding to package TypeScript code

Create a folder Directory structure: dabaots Init...

How to add vim implementation code examples in power shell

1. Go to Vim's official website to download t...

The difference between div and table in speed, loading, web application, etc.

1: Differences in speed and loading methods The di...

Use of Linux bzip2 command

1. Command Introduction bzip2 is used to compress...

Text mode in IE! Introduction to the role of DOCTYPE

After solving the form auto-fill problem discussed...

How to use MySQL group by and order by together

Suppose there is a table: reward (reward table), ...