How do I filter Map() values in JS?
I have a Map (), how can I check this collection if it contains an element that contains a specific character? If in other words, then for example there is such a list: Maxim, Ivan, Dmitry, Oleg, Alexey. The user enters some character(for example, " To") I need to write to the new list only those that contain this character. I.e., Maxim and Alexey should be written
var myMap = new Map();
var j = 0;
$('li', "#userlist").each(function () {
var user = this.textContent.toLowerCase().trim();
myMap.set(j, user);
array[j] = user;
j++;
});
var input = $('#search').val().toLowerCase();
var filteredList;
1
1 answers
Map
, in this case, it is not necessary, since Map
with an integer key is a regular array that does not have most of the familiar functions.
In the case of an array, you can try the method .filter
var filteredList = array.filter(el => el.indexOf(input) > -1);
In the case of Map
, there are several options for
- run through
Map
and delete unnecessary ones using the methodsforEach
anddelete
- use the spread operator to get an array keys/values, filter this array, and re-create
Map
, for example:var m = new Map([...oldMap].filter(el=> el[1].indexOf(input)>-1))
2
Author: Grundy, 2018-05-14 09:40:04