How to get and return each last character of array to be in uppercase using javascript?

Viewed 41

I have the following array variable, I want to return the given array where each of element's last character to be in Uppercase using javascript, I have tried like below, but I am getting undefined unfortunately, Could you please anyone help me to get the desired output like below. Thanks in advance.

Desired Output: [onE, twO, threE, fouR]

var arr = ['one', 'two', 'three', 'four'];

var res = arr.map((item) => {
    item.substr(arr.length) + item.charAt(arr.length -1).toUpperCase();
});
console.log(res);//[undefined, undefined, undefined, undefined]
2 Answers

you are missing a return statement:

var res = arr.map((item) => {
    return item.slice(0,-1)+item.slice(-1).toUpperCase()
});

You can also skip curly brackets and return keyword:

const arr = ['one', 'two', 'three', 'four'];

const res = arr.map(item => 
    item.substring(0, item.length - 1) +
    item.charAt(item.length - 1).toUpperCase()
)

console.log(res);

Also notice that String.prototype.substr is mentioned as deprecated (you can use substring instead).

Related