How to skip over an element in .map()?
Just .filter()
it first:
var sources = images.filter(function(img) {
if (img.src.split('.').pop() === "json") {
return false; // skip
}
return true;
}).map(function(img) { return img.src; });
If you don't want to do that, which is not unreasonable since it has some cost, you can use the more general .reduce()
. You can generally express .map()
in terms of .reduce
:
someArray.map(function(element) {
return transform(element);
});
can be written as
someArray.reduce(function(result, element) {
result.push(transform(element));
return result;
}, []);
So if you need to skip elements, you can do that easily with .reduce()
:
var sources = images.reduce(function(result, img) {
if (img.src.split('.').pop() !== "json") {
result.push(img.src);
}
return result;
}, []);
In that version, the code in the .filter()
from the first sample is part of the .reduce()
callback. The image source is only pushed onto the result array in the case where the filter operation would have kept it.
update — This question gets a lot of attention, and I'd like to add the following clarifying remark. The purpose of .map()
, as a concept, is to do exactly what "map" means: transform a list of values into another list of values according to certain rules. Just as a paper map of some country would seem weird if a couple of cities were completely missing, a mapping from one list to another only really makes sense when there's a 1 to 1 set of result values.
I'm not saying that it doesn't make sense to create a new list from an old list with some values excluded. I'm just trying to make clear that .map()
has a single simple intention, which is to create a new array of the same length as an old array, only with values formed by a transformation of the old values.
How I can skip the element of array .map?
This is what Array.prototype.filter()
is for. You need to do this in two steps.
var userids = userbody.contacts
.filter(contact => contact.iAccepted == 'true' && contact.contactAccepted == 'true')
.map(contact => contact.userId);
The filter part takes out all unnecessary elements, then map converts the rest to the way you want.
Skip element in array using map in javascript
You can use .filter()
on the mapped array:
let numbers = [4, 9, 16, 25];
let output1 = numbers.map(Math.sqrt).filter((_, i) => (i % 2 == 0));let output2 = numbers.map(Math.sqrt).filter((_, i) => (i % 2 != 0));
console.log(output1);console.log(output2);
Python: How to skip element in map function
You can skip the undesired element by filtering it with filter
:
inp = ['a','b','c']
inp_without_b = list(filter(lambda x: x != 'b', inp))
print(inp_without_b)
# Output: ['a', 'c']
Flutter : How to skip one element in map Iteration?
List<ImageProperty> _pictureListFromSnapShot(QuerySnapshot snapshot) {
List<dynamic> filterlist = snapshot.documents.where((doc){
return doc.data['creator_uid'] !=uid}).toList();
return filterlist.map((doc) {
return ImageProperty(
title: doc.data['title'] ?? null,
filename: doc.data['filename'] ?? null,
token: doc.data['token'] ?? null,
filelocation: doc.data['filelocation'] ?? null,
url: doc.data['url'] ?? null,
created: doc.data['created'] ?? null,
creator_uid: doc.data['creator_uid'] ?? null,
format: doc.data['format'] ?? null,
created_date: doc.data['created_date'].toString() ?? null,
timestamp: doc.data['timestamp'] ?? null,
tag_label: doc.data['tag_label'] ?? null,
user_tag: doc.data['user_tag'] ?? null,
rating: doc.data['rating'] ?? 0,
score: doc.data['score'] ?? 0,
display_count: doc.data['score_display_count'] ?? 0,
judges: doc.data['judges'] ?? null,
isClicked: false,
isShown: false,
);
}).toList();
}
2nd solution
List<ImageProperty> _pictureListFromSnapShot(QuerySnapshot snapshot)
{
List<ImageProperty> filterlist = []
snapshot.documents.forEach((doc) {
if(oc.data['creator_uid'] !=uid){
filterlist.add(ImageProperty(
title: doc.data['title'] ?? null,
filename: doc.data['filename'] ?? null,
token: doc.data['token'] ?? null,
filelocation: doc.data['filelocation'] ?? null,
url: doc.data['url'] ?? null,
created: doc.data['created'] ?? null,
creator_uid: doc.data['creator_uid'] ?? null,
format: doc.data['format'] ?? null,
created_date: doc.data['created_date'].toString() ?? null,
timestamp: doc.data['timestamp'] ?? null,
tag_label: doc.data['tag_label'] ?? null,
user_tag: doc.data['user_tag'] ?? null,
rating: doc.data['rating'] ?? 0,
score: doc.data['score'] ?? 0,
display_count: doc.data['score_display_count'] ?? 0,
judges: doc.data['judges'] ?? null,
isClicked: false,
isShown: false,
));
}
});
return filterlist;
}
How to skip certain elements when using javascript map()
One option is to just slice the array before you map, so in your case it would be:
this.props.message.split("\n").slice(1, -1).map((chunk) => {
return <span className="message-chunk">{chunk}<br /></span>
})
Note that this will remove the first and last element from the array. If you are intending to not modify the first or last element I recommend @vlaz's answer :)
How to skip first in map function
So slice it to skip the first
block.gallery.slice(1).map(...)
You also need to reference the item passed into map, not using the index with the orginal array.
block.gallery[i].images.thumbnail_sm
should be
item.images.thumbnail_sm
How can I use map() function to remove elements in an array?
Use .filter to remove elements, then apply needed action on them using .map
let serie = [7, 4, 9, 12, 18, 21];
const result = serie.filter(x => x > 10).map(x => x * 10)
console.log(result)
Skip over element in .map without adding .filter etc
It depends what you mean by "skip over element."
If you mean "don't include it in the output array," then you'll have to put map
aside, because map
will always produce an output element for an input element. Instead, you can just loop through pushing to a new array:
const originalItems = items;
items = [];
for (const item of originalItems) {
let user = users.find(u => item.user_id === u.id);
if (user) {
item.email = user.email;
item.user_name = user.name;
items.push(item);
}
}
If you just mean "don't add the user
information" (but do keep items you don't add information to), then you can just branch:
items = items.map((item) => {
let user = users.find(u => item.user_id === u.id);
if (user) {
item.email = user.email;
item.user_name = user.name;
}
return item;
});
That raises the question of why you're using map
at all, though, since there doesn't immediately seem to be much reason to create a new array with the same objects in it (even if we're adding to those objects). If you're using something like React where state updates must not modify existing objects, you'd want to create a new item
for any item you changed instead:
items = items.map((item) => {
let user = users.find(u => item.user_id === u.id);
if (user) {
item = {
...item,
email: user.email,
user_name = user.name,
};
}
return item;
});
But you may not be doing that, you haven't said.
Related Topics
Is There a Generic Way to Set State in React Hooks? How to Manage Multiple States
Understanding JavaScript Scope with "Var That = This"
Understanding What Goes on with Textarea Selection with JavaScript
Converting JSON Results to a Date
What Does Variable Declaration with Multiple Comma Separated Values Mean (E.G. Var a = B,C,D;)
Date Parsing in JavaScript Is Different Between Safari and Chrome
Regex for Number with Decimals and Thousand Separator
Downloading Canvas Element to an Image
How to Get the First Element of an Array
Skip Arguments in a JavaScript Function
No Semicolon Before [] Is Causing Error in JavaScript
How to Use Node.Js Module System on the Clientside
Is It a Good Idea to Learn JavaScript Before Learning Jquery
How to Display Binary Data as Image - Extjs 4
How Not to Forget Using Await Everywhere in JavaScript
How to Replace a Regex Substring Match in JavaScript
Dynamic Extension Context Menu That Depends on Selected Text
Why Are Certain Function Calls Termed "Illegal Invocations" in JavaScript