user19334054
user19334054

Reputation: 63

How to extract and manipulate items in an array Javascript

I am pretty new to Javascript and I am struggling with one of my assignments.

This is the context:

Manipulate this data

var grades = "jim|25, sue|32, mary|34, ann|22, ted|28, frank|15, lisa|19, mike|30, ahn|26, vishaya|27";

Create an HTML page with inline JavaScript code that displays student data in a more readable format like so:

Name1 - score1

Name2 - score2

Your program should:

Now, I was able to print the names and grades in a more readable format but I don't know how to go about capitalizing the first letter of each name and how to output the lowest, highest and average grades.

Here is my code:

  <body>
    <p id="demo"></p>
    <script>
      var grades =
        "jim|25, sue|32, mary|34, ann|22, ted|28, frank|15, lisa|19, mike|30, ahn|26, vishaya|27";

      let result = grades.split(", ");

      function getNameAndGrade(Str) {
        for (let i in result) {
          document.write(
            ` <b>Name: </b>${result[i].slice(
              0,
              result[i].indexOf("|")
            )} <b>Grade: </b>${result[i].slice(-2)} <br>`
          );
        }
      }
      getNameAndGrade(grades);
    </script>
  </body>

Upvotes: 0

Views: 74

Answers (2)

Alexander Petrushyn
Alexander Petrushyn

Reputation: 58

You need some refactoring.

First of all, don't let your function write directly to the DOM. Instead, make it return your desired data and prefer modular structure (functions are small and do only one tiny specific task)

function getNameAndGrade(couple) {
    return {
        name: couple.split('|')[0],
        score: couple.split('|')[1]
    }
}

To capitalize the first letter, get it with substring method (0 is the position of the substring and 1 is a substring length) and then capitalize it with capitalize. After that, add the rest of your string with substring(1) (1 means here without 1 first letter).

function capitalizeFirstLetter(string) { 
    string.substring(0, 1).toUpperCase() + string.substring(1)
}

It is a good practise to separate your logic and view. This means, one function for calculations and another one for writing it to the screen. It helps you reuse your code.

function displayCouples(couples) {
    const displayData = couples.map(couple => 
        `<b>${capitalizeFirstLetter(couple.name)}</b>: ${couple.score}`
    )
    document.getElementById('demo').innerHTML = displayData
}

To get min, max and average score, we use method map. The only thing it is doing is putting the score instead of the whole name and score object into our math functions. It tells javascript to take the score field and not the whole object.

function getAverageScore(couples) {
    return Math.sum(...pairs.map(couple => couple.score)) / couples.length
}

function getMaxScore(couples) {
    return Math.max(...couples.map(couple => couple.score))
}

function getMinScore(couples) {
    return Math.min(...couples.map(couple => couple.score))
}

And here all the work:

const input = "jim|25, sue|32, mary|34, ann|22, ted|28, frank|15, lisa|19, mike|30, ahn|26, vishaya|27"

// we use hetNameAndGrade inside map function. It means, we apply this function to every pair of name and score
const pairs = input.split(', ').map(getNameAndGrade)

displayCouples(pairs)

const min = getMaxScore(pairs)
const max = getMaxScore(pairs)
const average = getAverageScore(pairs)

Upvotes: 1

TheVS
TheVS

Reputation: 101

For capitalizing words, you can use a mixture of three functions: charAt(), toUpperCase() and slice().

The charAt() function returns the character at a given position in a string. Example:

const str = 'javascript';
const str2 = str.charAt(0);
console.log(str2);

//Output: j

The toUpperCase() function converts all the characters of an input string to uppercase. Example:

const str = 'javascript';
const str2 = str.toUpperCase();
console.log(str2);

//Output: JAVASCRIPT

Now, everything is capitalized. We, however need only the first letters to be capitalized. To capitalize the first character of a string, we can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.

The slice() function slices a given string from a specified “start” position until the specified “end” position. Example:

const str = 'javascript';
const str2 = str.slice(1);
console.log(str2);

//Output: avascript

So, we'll use all three of those to capitalize the first letters.

const str = 'javascript';
const str2 = str.charAt(0).toUpperCase() + str.slice(1);
console.log(str2);

//Output: Javascript

Upvotes: 0

Related Questions