so before anything my experience with JavaScript is not that much, I'm trying to make a function called hashtag_it with an array and i want to add # before every index in this array so when I call the function the output is going to be #programming,#code , i tried to use array.join method but it didn't really work
function hashtag_it(my_array) {
my_array = ['programming','code'];
console.log(my_array.join('#'))
}
console.log(hashtag_it());
CodePudding user response:
const my_array = ['programming','code'];
function hashtag_it() {
return my_array.map(item => `#${item}`).join(',');
}
console.log(hashtag_it(my_array));
.join
only joins by a separator after each element. You want to add #
before each element. What I have changed is I have added map
which simply appends #
before each element and then you can use join(',')
which joins each element using a ,
as a separator
References:
CodePudding user response:
You have to add #
to all the elements in the array and then join it. Simply using join won't add #
to the first element.
function hashtag_it(my_array) {
my_array = ['programming', 'code'];
new_array = my_array.map(el => "#" el).join(",")
return new_array
}
console.log(hashtag_it());
CodePudding user response:
const array = ["programming", "coding", "dogs"];
const tagIt = (arr) => {
return arr.map(word => '#' word).join(",");
};
console.log( tagIt(array) );