How To Add Text To End Of Each Array Element Using Map?
Solution 1:
.map
's callback function expects a return value
let arr = ["England", "Scotland", "Westeros"];
dragonMapper = arr => {
let newArr = arr.map(function(e) {
return e + '...here be dragons'; //Return the concatenated value of 2 strings
});
return newArr;
}
console.log(dragonMapper(arr));
Shorter version, with the arrow function syntax:
let arr = ["England", "Scotland", "Westeros"];
dragonMapper = arr => {
return arr.map(e => e + '...here be dragons');
}
console.log(dragonMapper(arr));
Solution 2:
You can do it using the .map()
method and template literals:
let arr = ["England","Scotland","Westeros"];
let result = arr.map(country =>`${country}...here be dragons`);
console.log(result);
Solution 3:
Instead of e += '...here be dragons'
you can simply do e + '...here be dragons'
and return the new value.
Also, you are calling dragonMapper
with newArr
but it needs to be called with arr
let arr = ["England", "Scotland", "Westeros"];
dragonMapper = (arr) => {
return arr.map(function(e) {
return e + '...here be dragons'
});
}
console.log(dragonMapper(arr));
Solution 4:
As others have said, you can fix this with code like this:
let arr = ["England","Scotland","Westeros"];
let dragonLands = arr.map(country => country + '...here be dragons');
console.log(dragonLands);
But also important is to understand why your code fails. The issue is that Strings are immutable. So this:
e += '...here be dragons'
does not change the value of e
in your original array but instead returns a new String, which is immediately thrown away, since you don't assign it to something or return it.
It can be confusing because this looks fairly similar:
let arr = [
{name: "England", id: 1},
{name: "Scotland", id: 2},
{name: "Westeros", id: 3}
];
arr.forEach(country => country.name += '...here be dragons');
console.log(arr);
But there are important differences. First, map
returns the result of applying the function to the elements. forEach
, in contrast, is only important for side effects, in this case mutating the elements supplied to it.
Second, country => country.name += '...here there be dragons'
does two things. It creates a new String as did your version, but then it assigns it back to country.name
. Objects are not immutable.
map
is an extremely useful construct, but when using it, it's essential to understand that it's the result of the function it invokes that's important.
Post a Comment for "How To Add Text To End Of Each Array Element Using Map?"