I would like to filter an array of items by using the map()
function. Here is a code snippet:
var filteredItems = items.map(function(item) { if( ...some condition... ) { return item; } });
The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.
Any idea?
EDIT: Thanks, I forgot about filter()
, what I wanted is actually a filter()
then a map()
.
EDIT2: Thanks for pointing that map()
and filter()
are not implemented in all browsers, although my specific code was not intended to run in a browser.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.
splice() function. The splice() method in JavaScript is often used to in-place add or remove elements from an array. The idea is to find indexes of all the elements to be removed from an array and then remove each element from the array using the splice() method.
You should use the filter
method rather than map unless you want to mutate the items in the array, in addition to filtering.
eg.
var filteredItems = items.filter(function(item) { return ...some condition...; });
[Edit: Of course you could always do sourceArray.filter(...).map(...)
to both filter and mutate]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With