I am trying to reverse a string in JavaScript using Reduce method. But I am getting an error. Can anyone suggest me how to solve an error?
code ::
var reverseString = function(s) {
return s.split("").reduce((rev, char) => char + rev, '');
};
reverseString(['h', 'e', 'l', 'l', 'o']);
output ::
I am trying to reverse a string in JavaScript using Reduce method. But I am getting an error. Can anyone suggest me how to solve an error?
code ::
var reverseString = function(s) {
return s.split("").reduce((rev, char) => char + rev, '');
};
reverseString(['h', 'e', 'l', 'l', 'o']);
output ::
Share Improve this question edited Mar 30, 2019 at 1:09 Riya asked Mar 30, 2019 at 1:02 RiyaRiya 42510 silver badges25 bronze badges 7-
You're passing it an array.
.split()
is for strings not arrays. I think you wanted.join()
– Aniket G Commented Mar 30, 2019 at 1:03 - Pass the string in as 'hello' not as an array. – Vappor Washmade Commented Mar 30, 2019 at 1:03
- 2 Please post actual code not images of code. Nobody can copy it to test or modify for answers. minimal reproducible example Also provide expected results – charlietfl Commented Mar 30, 2019 at 1:04
-
2
I don't think
.reduce()
is the right tool for the job. – Pointy Commented Mar 30, 2019 at 1:05 - Indeed, it appears there is already a function which will do this. – Heretic Monkey Commented Mar 30, 2019 at 1:12
3 Answers
Reset to default 4You almost had it, just needed to remove the String.prototype.split()
method, because String.split()
doesn't work on arrays. Example:
var reverseString = function(s) {
return s.reduce((rev, char) => char+rev, "").split("");
}
console.log(reverseString(['h', 'e', 'l', 'l', 'o']));
Check if you really want to reverse a string or an array. Try this if it's a string
var reverseString = function(s) {
return s.split('').reverse().join('');
}
console.log(reverseString('hello'));
function reverseString(str) {
return str.split('').reduce((rev, char) => char + rev, "");
}
or
function reverseString(str) {
return str.split('').reverse().join('')
}