Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' ]
like image 281
Tsardines Avatar asked Jan 20 '26 09:01

Tsardines


1 Answers

Map instead of filtering - inside the callback, if even, return the capitalized portion, else return the original string:

function alts(arr) {
  return arr.map((str, i) => i % 2 === 1 ? str : str[0].toUpperCase() + str.slice(1));
}

console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));
like image 181
CertainPerformance Avatar answered Jan 22 '26 22:01

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!