Reputation: 97
The definition in my book is the method passes each element of the array on which it is invoked to the function you specify, and returns a new array containing the value returned by that function.
a = [1,2,3]
a.map(function(x) { return x*x; }); // b is [1,4,9]
I would want the function to only return 1 if 4 is not found.
The case would be
var bool = false;
a.map(function(x) {
if (x == 4){
bool = true;
}
return x;
}).filter(function(x) {if( (x == 1) && ( bool = true)){ return null}});
The way I would like to use it is by iterating over an array and than dynamically change the map at the end. How would I do that?
My problem now is with strings, so Here is another case, where 1 is now called unknown. And if anything after "unknown" is found, remove "unknown" from the list before joining.
var wordList = [];
var newSource = false;
str = results[i].Meaning.map(function(m){
count++;
if ((!m.Source && !contains(wordList, "unknown"))) {
wordList[count] = "unknown";
return "unknown";
}
if (!m.Source ) {
return m.Source;
}
if ( contains(wordList, "unknown") ) {
newSource = true;
}
if (!contains(wordList, m.Source) ) {
wordList[count] = m.Source;
return m.Source;
}
}).filter(function(x) { return x }).filter(function(x){
if (newSource == true ) { return (x != "unknown")}}).join(', ');
Upvotes: 0
Views: 971
Reputation: 741
Let's look at the first function:
function f1(x) {
var bool = false;
if (x == 4){
bool = true;
}
return x;
}
This function changes the variable bool
locally, and returns x
. So, no matter what happens to bool
, this function is equivalent to the identity function:
function(x) { return x; }
Because .map(f)
returns an array with f
applied to all elements, we have that a.map(f1)
is equivalent to a.map(identity function)
which is equivalent to a
.
The second function is inside the filter:
if( (x == 1) && ( bool = true)) return null;
We have some issues here:
function(x)
signaturebool
variable, that was declared on the first function.I suggest whenever you use map
and filter
, that you use pure functions, which means your function just process the parameter passed to them, and return the result.
I'm not sure what you are trying to accomplish in the first problem; please give more details and I'll try to help you with a solution.
Look for tutorials in map, filter and reduce on Google. For example, this egghead video.
Upvotes: 2