Skip to content
Advertisement

Capitalize first letter of every other array element

I have an array of elements, ["apple", "cherry", "raspberry", "banana", "pomegranate"], and I want it so that every odd element is capitalized: ["Apple", "cherry", "Raspberry", "banana", "Pomegranate"].

I can capitalize every element in the array, and I can filter out every odd element, but not at the same time (i.e. filtering only shows the odd elements).

Does anyone have any approaches and/or recommendations for this? I’ve seen questions about capitalizing every other letter, retrieving every other array element, etc., but nothing like what I’ve asked (yet, I’m still looking).

function alts(arr) {
    const newArr = arr.filter((el, idx) => {
        if (idx % 2 === 0) {
            return arr.map(a => a.charAt(0).toUpperCase() + a.substr(1));
        }
    })
    return newArr;
}

console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));
// Just returns [ 'apple', 'raspberry', 'pomegranate' ]

Advertisement

Answer

Try this:

function alts(arr) {
    return arr.map((el, idx) => {
        return idx % 2 == 0 ? el.charAt(0).toUpperCase() + el.substr(1) : el;
    })
}

console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));

I map through the array and if the element’s index is even (that’s because index starts from 0, so it’s flipped for us as we start counting from 1) then return the element with first letter capitalized, if it’s an odd index, then just return the element itself.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement