user4727873
user4727873

Reputation:

Use filter and map methods to capitalize the first letter of certain elements within an array - JavaScript

I am trying to accomplish capitalizing the first letter of certain elements within an array. I am needing to skip the elements that begin with the letter c. I am also required to use the filter and map methods. I viewed the documentation at MDN and I am at a loss. This is for school, so I really need to understand why the code works; I am not just looking for the answer. Here is my html:

<div><strong>Sorted Fruit:</strong> <span id="sorted-fruit"></span></div>
<div><strong>Capitalized Fruit without Cs:</strong> <span id="capitalized-fruit"></span></div>

Here is my JS:

// (1) Iterate through each fruit type and write it to the console 
//      using a for loop.
// (2) Use Array's methods "sort" and "join" to print an alphabetically 
//      sorted comma delimited list of fruit in the span with id "sorted-fruit"
// (3) Use ECMAScript 5 Array methods "filter" and "map" and Array method 
//      "join" to print out a comma delimited list of fruit that are 
//      capitalized (just the first letters); skip those that contain the 
//      letter "c" in them.

(function() {

    var fruit = [
        "apple",
        "orange",
        "peach",
        "cherry",
        "pear",
        "apricot",
        "banana",
        "guava",
        "melon"
    ];

    fruit.sort();
    var myFruit = fruit.join(', ');
    for (i = 0; i < fruit.length; i++) {
         console.log(myFruit);
         }

    document.getElementById('sorted-fruit').innerHTML = myFruit;
    // Your code goes here ...

}());

Upvotes: 1

Views: 3227

Answers (2)

If you wanted to shorten what you need to write in code arrow functions are great!

// To capitalize the first letter of remaining words, using 'w' as the variable for each word
const fruit = fruit.map(w => w.charAt(0).toUpperCase() + w.slice(1));

var fruit = [
  "apple",
  "orange",
  "peach",
  "cherry",
  "pear",
  "apricot",
  "banana",
  "guava",
  "melon"
]
const fruitChanged = fruit.map(w => w.charAt(0).toUpperCase() + w.slice(1));

console.log(fruitChanged)

Also the map array method is great if you are going to iterate through an array. MDN - Array Method: Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Upvotes: 2

Drakes
Drakes

Reputation: 23660

Your part 3 solution:

// Filter out entries with the letter 'c'
fruit = fruit.filter(function (el) {
    return el.indexOf('c') === -1;
});

// Capitalize the first letter of all remaining strings
fruit = fruit.map(function(string){ 
    return string.charAt(0).toUpperCase() + string.slice(1);
});

But I want you to take apart this solution and figure out what it is doing.

Upvotes: 0

Related Questions