Array.prototype.filter()
Метод filter() создаёт новый массив со всеми элементами, прошедшими проверку, задаваемую в передаваемой функции.
Интерактивный пример
Синтаксис
// Стрелочная функция filter((element) => . > ) filter((element, index) => . > ) filter((element, index, array) => . > ) // Колбэк-функция filter(callbackFn) filter(callbackFn, thisArg) // Встроенная колбэк-функция filter(function callbackFn(element) . >) filter(function callbackFn(element, index) . >) filter(function callbackFn(element, index, array) . >) filter(function callbackFn(element, index, array) . >, thisArg)
Параметры
Функция-предикат, которая будет вызвана для проверки каждого элемента массива. Если функция возвращает true , то элемент остаётся в массиве, если false , то удаляется.
Принимает три аргумента
Текущий обрабатываемый элемент в массиве.
Индекс текущего обрабатываемого элемента в массиве.
Обрабатываемый массив, на котором был вызван метод filter() .
Значение, используемое в качестве this при вызове колбэк-функции callbackFn .
Возвращаемое значение
Вернётся новый массив с элементами, которые прошли проверку. Если ни один элемент не прошёл проверку, то будет возвращён пустой массив.
Описание
Метод filter() вызывает переданную функцию callback один раз для каждого элемента, присутствующего в массиве, и создаёт новый массив со всеми значениями, для которых функция callback вернула значение, которое может быть приведено к true . Функция callback вызывается только для индексов массива с уже определёнными значениями; она не вызывается для индексов, которые были удалены или которым значения никогда не присваивались. Элементы массива, не прошедшие проверку функцией callback , просто пропускаются и не включаются в новый массив.
Функция callback вызывается с тремя аргументами:
- значение элемента;
- индекс элемента;
- массив, по которому осуществляется проход.
Если в метод filter() был передан параметр thisArg , при вызове callback он будет использоваться в качестве значения this . В противном случае в качестве значения this будет использоваться значение undefined . В конечном итоге, значение this , наблюдаемое из функции callback , определяется согласно обычным правилам определения this .
Метод filter() не изменяет массив, для которого он был вызван.
Элементы массива, обрабатываемые методом filter() , устанавливается до первого вызова функции callback . Элементы, добавленные в массив после начала выполнения метода filter() , либо изменённые в процессе выполнения, не будут обработаны функцией callback . Соответствующим образом, если существующие элементы удаляются из массива, они также не будут обработаны
Предупреждение: одновременное изменение элементов, описанное в предыдущем параграфе, часто приводит к труднопонимаемому коду, поэтому не рекомендуется делать это (за исключением особых случаев).
Примеры
Фильтрация всех маленьких значений
Следующий пример использует filter() для создания отфильтрованного массива, все элементы которого больше или равны 10, а все меньшие 10 удалены.
function isBigEnough(value) return value >= 10; > let filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // массив filtered теперь содержит [12, 130, 44]
Найти все простые числа в массиве
Следующий пример возвращает все простые числа в массиве:
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isPrime(num) for (let i = 2; num > i; i++) if (num % i == 0) return false; > > return num > 1; > console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
Фильтрация неверных записей в JSON
В следующем примере метод filter() используется для создания отфильтрованного JSON-объекта, все элементы которого содержат ненулевое числовое поле id .
let arr = [ id: 15 >, id: -1 >, id: 0 >, id: 3 >, id: 12.2 >, >, id: null >, id: NaN >, id: "undefined" >, ]; let invalidEntries = 0; function filterByID(item) if (Number.isFinite(item.id) && item.id !== 0) return true; > invalidEntries++; return false; > let arrByID = arr.filter(filterByID); console.log("Отфильтрованный массив\n", arrByID); // Отфильтрованный массив // [< id: 15 >, < id: -1 >, < id: 3 >, < id: 12.2 >] console.log("Количество некорректных элементов token punctuation">, invalidEntries); // Количество некорректных элементов = 5
Поиск в массиве
В следующем примере filter() используется для фильтрации содержимого массива на основе входных данных.
var fruits = ["apple", "banana", "grapes", "mango", "orange"]; /** * Элементы массива фильтруется на основе критериев поиска (query) */ function filterItems(query) return fruits.filter(function (el) return el.toLowerCase().indexOf(query.toLowerCase()) > -1; >); > console.log(filterItems("ap")); // ['apple', 'grapes'] console.log(filterItems("an")); // ['banana', 'mango', 'orange']
Реализация с использованием ES2015
const fruits = ["apple", "banana", "grapes", "mango", "orange"]; /** * Элементы массива фильтруется на основе критериев поиска (query) */ const filterItems = (arr, query) => return arr.filter( (el) => el.toLowerCase().indexOf(query.toLowerCase()) !== -1, ); >; console.log(filterItems(fruits, "ap")); // ['apple', 'grapes'] console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
Модификация изначального массива (изменение, добавление и удаление)
В следующих примерах проверяется поведение метода filter при изменении массива.
// Изменение всех элементов let words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const modifiedWords = words.filter((word, index, arr) => arr[index + 1] += " extra"; return word.length 6; >); console.log(modifiedWords); // Обратите внимание, что есть три слова длиной менее 6, но так как они были изменены, // возвращается одно слово ['spray'] // Добавление новых элементов words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const appendedWords = words.filter((word, index, arr) => arr.push("new"); return word.length 6; >); console.log(appendedWords); // Только три слова удовлетворяют условию, хотя `words` теперь имеет куда больше слов, // длинной меньше 6 символов: ['spray', 'limit', 'elite'] // Удаление элементов words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const deleteWords = words.filter((word, index, arr) => arr.pop(); return word.length 6; >); console.log(deleteWords); // Заметьте, что 'elite' не получено, так как удалено из `words` до того, // как filter смог получить его: ['spray', 'limit']
Спецификации
| Specification |
|---|
| ECMAScript Language Specification # sec-array.prototype.filter |
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
- Полифил Array.prototype.filter в библиотеке core-js
- Array.prototype.forEach()
- Array.prototype.every()
- Array.prototype.some()
- Array.prototype.reduce()
- Array.prototype.find()
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 6 янв. 2024 г. by MDN contributors.
Your blueprint for a better internet.
Webix UI 4.4 Release Overview

The new release 4.4 of Webix JavaScript UI library is available for download. Let’s have a look at the changes and new functionality: Print API, Query Builder, Demos of Integration with PHP, Node.js and .NET.
Printing from Applications
- the print area
- the paper size
- the margins
- page orientation and scale
- headers, grid lines and empty rows printing
The variety of printing options depends on the type of a widget. The complex widget Spreadsheet features a built-in printing functionality:
Advanced Filtering
Query Builder, the 89th Webix widget, is a constructor of complex rules for filtering. You can use it with any data components of the library. From now on, the DataTable widget allows using the Query Builder as a built-in filter.
The new widget allows building complex filters by grouping several rules (or even groups of rules) based on the specified conditions (AND or OR). Each rule includes a criterion that the filtered values should meet. Query Builder widget is available only for Webix PRO.
Clear Integration with Backend Platforms
The new demos, that can be found on GitHub, are aimed at simplifying integration with:
The demos show how to connect Webix UI with these backend platforms. We are planning to expand the list of demos on integration with backend platforms.
The Site Update
You must have noticed that the Webix site looks different. We are doing our best to keep up with the times and gradually adding new parts to the site. We have added a page with video tutorials, simplified the form on the Trial download page of Webix PRO with all complex widgets, upgraded the license page. From now on you can add the necessary number of licenses for complex widgets to your Team Pack.
Minor Changes
Disabled menu items
We added the special attribute for the Menu widget. This attribute allows disabling certain menu items during the initialization of the component.
Updated integration with Google Maps
Integration with Google Maps was improved and included into the library as a separate widget. Since version 4.4 we have removed the outdated integration from the components repository on GitHub and from CDN.
You can find the complete list of changes on the What’s new page.
Try the Trial version of Webix PRO with complex widgets Pivot, Kanban, Scheduler, Spreadsheet, File Manager and feel free to give your feedback. Clients with an active license can download the new release from the Client Area or via CDN.
Meanwhile we are working on release 5.0. It will include awesome updates and long-expected features
Written by
- Bio
- Latest Posts
Filter Builder in Javascript
Anyone knows a javascript alternative to something like: http://demos.devexpress.com/ASPxGridViewDemos/Filtering/FilterBuilder.aspx -> click on the condition in the footer of the grid to see the filter Can be a jquery plugin, jqGrid plugin or anything. Any suggestion appreciated, thanks.
asked Nov 4, 2011 at 11:58
344 6 6 silver badges 14 14 bronze badges
3 Answers 3
There is an open source project in Google Code, which meets your requirement. Checkout the demo here: http://expbuilder.googlecode.com/hg/src/cb/condition-builder.html
Edit: Google Code is no longer active but if you’re really interested in trying this old answer, you can download the source code here: https://code.google.com/archive/p/expbuilder/source/default/source
answered Oct 19, 2012 at 18:15
577 7 7 silver badges 25 25 bronze badges
Download link would be convenient :D.
Feb 25, 2013 at 8:06
I checked Paramesh solution and found it good enough for me.
However while integrating with project, I found js is rather lacking more modern jQuery features, as well as it can be simplified. So I did.
My alternative solution:
Maybe someone will find it useful some day.
Feel free to copy/paste/change/suggest fixes/suggest features. 😉
Saved searches
Use saved searches to filter your results more quickly
Cancel Create saved search
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
feat(*): add ability extract resources in specific folder #186
blazarev wants to merge 1 commit into alfa-laboratory : master
base: master
Choose a base branch
Branches Tags
Could not load branches
Branch not found: >
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
feat(*): add ability extract resources in specific folder #186
blazarev wants to merge 1 commit into alfa-laboratory : master from blazarev : master
Conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
blazarev commented Mar 26, 2018
суть PR в том, что бы дать возможность пользователям складывать файлы (иконки, шрифты и прочее что проходит через file-loader) в отдельный каталог по нужному пути.
к примеру сейчас что бы обойти это ограничение приходится прибегать к подобному хаку
config.module.rules .filter(item => /file-loader/.test(item.loader)) .forEach((item) => < if (item.options && item.options.name) < item.options.name = `$[name].[hash].[ext]`; > >);
artptr commented Mar 26, 2018
А для каких целей может такое понадобиться?
blazarev commented Mar 27, 2018 •
- сделать консистентно обработке css — для css такая опция есть изначально.
- с целью складывать всю статику в конкретный суб каталога внутри билда и сервить его (сейчас это делает node.js на нашем проекете к примеру). Накидывать всё в рутовый каталог так себе выглядит.
по css — webpack.production-builder.js
const extractMainCSS = new ExtractTextPlugin(options.extractMainCSS || '[name].[hash].css'); const extractIconsCSS = new ExtractTextPlugin(options.extractIconsCSS || '[name]-icons.[hash].css');
artptr commented Mar 27, 2018
Так в стабе уже предусмотрено, что вся статика кладётся в каталог assets. Кроме неё там ничего нет. Управляется это заданием параметра output.path в вебпаке.
blazarev commented Mar 27, 2018 •
outputh.path выставлен как .build и именно туда попадают файлы обработанные file-loader. не в каталог assets.
Помимо этого возможность выбирать каталог для экспорта ресурсов должна быть на уровне библиотеки пресетов, а не стаба (которым кстати не все пользуются).
ps — к тому же PR не ломает обратной совместимости — то что работало, будет работать и дальше)
artptr commented Mar 27, 2018
Не совсем понятно, в чём отличие клиентских скриптов и стилей от картинок и шрифтов, чтобы физически их разделять. И то, и другое нужно сёрвить. Если даже хочется отделить клиентские скрипты, стили и всё остальное, то дробить уже по их типам, а не в зависимости от лоадера.
blazarev commented Mar 27, 2018 •
не не, физически вся статика будет попадать в отдельный каталог, а из корня только server.js крутится с нодой которая и сервит статику.
я к тому, что для css(пример выше в комментах) и js( кусок секции output — filename: isProd ? $[name].[hash].js : $[name].js ) есть возможность положить их в отдельный каталог, а ресурсы которые проходят через file-loader попадают в корень билда а не в нужную папку.
artptr requested review from tx44 and Heymdall April 4, 2018 21:08
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
2 participants
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.