0
var scratchData = [   
  {name: 'Billy Boy', grade: 'D'},
  {name: 'Serious Sara', grade: 'B'},  
  {name: 'Tepid Tom', grade: 'C'} ];  


function makeStudentsReport(data)  

How can i make this function return a string that say name + 'is getting an' + grade; I must return an object.

4
  • do you need an array with the strings? Commented Feb 12, 2017 at 9:58
  • Return an Object or return a string? What did you try? Commented Feb 12, 2017 at 10:00
  • return a object. I've tried console.log(scratchData.name +'is getting an' + scratchData.grade) Commented Feb 12, 2017 at 10:07
  • You need to loop or map the array. for (var i=0;i<scratchData.length;i++) { console.log(scratchData[i].name+' is getting a(n) '+ scratchData[i].grade); } Commented Feb 12, 2017 at 10:17

2 Answers 2

2

You could map the result strings with Array#map

function makeStudentsReport(data)  {
    return data.map(function (a) {
        return a.name + ' is getting a' + ('AEF'.indexOf(a.grade) === -1 ? "" : "n" ) + ' ' + a.grade;
    });
}

var scratchData = [{ name: 'Billy Boy', grade: 'D' }, { name: 'Serious Sara', grade: 'B' }, { name: 'Tepid Tom', grade: 'C' }, { name: 'Jet Jane', grade: 'A' }];

console.log(makeStudentsReport(scratchData));

Sign up to request clarification or add additional context in comments.

4 Comments

..is getting a"+("AEF".indexOf(a.grade)==-1?"n":"") + a.grade
@mplungjan, nice catch. but result strings are reversed.
Ah. !=-1 as I had when I wrote it, then I swapped it but forgot to swap the n too
i used the .map method and it worked!! Thank you for your help!!
0

Well David, you can use the map function as well as Nina did, or you can just use the typical for loop way:

var scratchData = [   
  {name: 'Billy Boy', grade: 'D'},
  {name: 'Serious Sara', grade: 'B'},  
  {name: 'Tepid Tom', grade: 'C'} ];

var get = ' is getting an '; // declaring it with var so it's easier to use

function makeStudentsReport(data) { // data  will be the array
    for (var i = 0; i < data.length; i++){
        var everyObject = data[i]; //  everyObject is every object in the array
        console.log(everyObject.name + get + everyObject.grade);
    }
}
makeStudentsReport(scratchData); // passing the array as a parameter to the function

Or more simple you can use Array.forEach() method:

function makeStudentsReport(data) {
    data.forEach(function(object){
        console.log(object.name + get + object.grade);
    });
}

makeStudentsReport(scratchData);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.