• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Filtering an array of objects based on a condition

Filtering an array of objects based on a condition

Filtering an array of objects based on a condition

If you have a large array of data and want to filter out items based on a specific condition then you can simply use the filter function. In this example we have an array of file paths. Some files are in ‘dir1’ while others are in ‘dir2’. Let’s say we want to filter for only a specific directory:

let data = [
  "files/dir1/file",
  "files/dir1/file2",
  "files/dir2/file",
  "files/dir2/file2"
];
let filteredData = data.filter(path => path.includes('dir2'));
console.log(filteredData);
--> [ 'files/dir2/file', 'files/dir2/file2' ]

Filtering for a specific directory within the above array of paths is easy. By specifying that the path string must include the string ‘dir2’ you will filter out any paths that don’t contain ‘dir2’ in them. Remember whatever function you pass to filter must return true for the item to be included in the result.

Source

https://levelup.gitconnected.com/6-javascript-code-snippets-for-solving-common-problems-33deb6cacef3

Miscellaneous

Related Snippets:

  • 3 Ways To Find an Object by ID in a JavaScript Array
  • Remove duplicate items from an array
  • Copy text to the clipboard
  • Count elements in an array

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers