D3.js selection.filter() Function

The d3.selection.filter() function in d3.js is used to filter the given selection and return a new selection for which the filter is true. The filter to be used may be a string or a function.
Syntax:
selection.filter(filter);
Parameters: This function accepts one parameter as mentioned above and described below:
- filter: It is a string or a function that would be used to filter a selection. The filter is applied to each selected element when using a function.
Return Values: This function returns the new selection.
Example 1: This example selects all the odd children of the specified element.
HTML
| <!DOCTYPE html> <htmllang="en">  <head>     <metacharset="UTF-8">     <metaname="viewport"content=         "width=device-width,initial-scale=1.0">          <scriptsrc=     </script>     <scriptsrc=     </script> </head>  <body>     <div>         <b>1. This text is in bold</b>         <b>2. This text is also in bold</b>         <b>3. Geeks for zambiatek</b>         <b>4. Geeks for zambiatek</b>         <b>5. Geeks for zambiatek</b>     </div>         <script>         let selection = d3.selectAll("b")             .filter(":nth-child(odd)")             .nodes();         selection.forEach((e) => {             console.log(e.textContent)         })     </script> </body>  </html>  | 
Output:
Example 2: This example selects all the even children of the specified element.
HTML
| <!DOCTYPE html> <htmllang="en">  <head>     <metacharset="UTF-8">     <metaname="viewport"content=         "width=device-width,initial-scale=1.0">     <scriptsrc=     </script>     <scriptsrc=     </script> </head>  <body>     <div>         <b>1. This text is in bold</b>         <b>2. This text is also in bold</b>         <b>3. Geeks</b>         <b>4. Geeks</b>         <b>5. Geeks for zambiatek</b>     </div>          <script>         let selection = d3.selectAll("b")             .filter(":nth-child(even)")             .nodes();         selection.forEach((e) => {             console.log(e.textContent)         })     </script> </body>  </html>  | 
Output:
Example 3: This example uses selection.selectAll as a filter.
HTML
| <!DOCTYPE html> <html>  <head>     <metacharset="UTF-8">     <metaname="viewport"content=         "width=device-width, initial-scale=1.0">      <scriptsrc=     </script>     <scriptsrc=     </script> </head>  <body>     <div>         <h3>1. This text is in bold</h3>         <h3>2. This text is also in bold</h3>         <h3>3. Geeks</h3>         <h3>4. Geeks</h3>         <h3>5. Geeks for zambiatek</h3>     </div>          <script>          // Using selection.selectAll with filter         let selection = d3.selectAll("div")             .selectAll("h3")             .filter(":nth-child(even)")             .nodes();         selection.forEach((e) => {             console.log(e.textContent)         })     </script> </body>  </html>  | 
Output:
 
				 
					



