简体   繁体   中英

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 (ie 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' ]

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"]));

You can use a simple for-loop as follows:

 function alts(arr=[]) { const newArr = [...arr]; for(let i = 0; i < newArr.length; i+=2) { const current = newArr[i]; if(current) newArr[i] = current.charAt(0).toUpperCase() + current.substr(1); } return newArr; } console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));

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.

 function alts(arr) { return arr.map((item, index) => { if (index % 2 === 0) { return item.charAt(0).toUpperCase() + item.substr(1); } else { return item } }); } console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"])); // Just returns [ 'apple', 'raspberry', 'pomegranate' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM