Reputation: 6166
I have an array like this:
["name1", "name2", null, null, "name5", null]
I want to make it like this:
["name1 wow", "name2 wow", null, null, "name5 wow", null]
I tried to do it like this:
myCtrl.myArray.map(s => s + " wow");
Seems it's not the right solution, any ideas?
Upvotes: 2
Views: 57
Reputation: 68933
Try Aarry's map()
with the help of ternary operator like the following:
var arr = ["name1", "name2", null, null, "name5", null];
var res = arr.map(function(item){
return item != null ? item + ' wow' : null;
});
console.log(res);
Upvotes: 3
Reputation: 5049
For the sake of completeness, you don't actually have to compare to null
:
var arr = ["name1", "name2", null, null, "name5", null];
var res = arr.map(function(item) {
return item ? item + ' wow' : null;
});
console.log(res);
Upvotes: 0
Reputation: 386540
You could use a logical AND &&
for checking falsy values and return the falsy value direcly or concat the value with a postfix.
You need to assign the result array of Array#map
to a new or the old variable.
var array = ["name1", "name2", null, null, "name5", null],
result = array.map(s => s && s + " wow");
console.log(result);
Upvotes: 2
Reputation: 1146
Add condition for null
checking
let a = ["name1", "name2", null, null, "name5", null];
console.log(a.map(s => s == null ? null : (s + ' wow') ));
Upvotes: 1
Reputation: 1454
Do your adding stuff only if s
is not null
myCtrl.myArray.map(s => (s==null?null:s + " wow"));
Upvotes: 1