In: Computer Science
JavaScript - Create a class using "names" as the identifier.
Create a constructor. The constructor must have elements as
follow:
first ( value passed will be String )
last ( value passed will be String )
age ( value passed will be Numeric )
The constructor will assign the values for the three elements and should use the "this" keyword
Create a function, using "printObject" as the identifier
printObject:
This function will have three input parameters:
allNames , sortType, message
Will sort the array of objects (allNames) using sortType as the
key to how the arrays objects will be sorted.
These sort functions, are higher order functions, one required for
each sort option except none. A higher order function type is
calling a function with an argument that is a function. In this
assignment, one would be using the builtin sort for arrays,
allNames.sort( your function here ); This function will override
the default sort order, built into array.sort()
The sort options are first , last , age, none.
Will print the message to the console
Will use a loop to print out the array by index ascending and
display the values located in the elements: first last age, for
each index accessed
Create a function main, no input parameters
main:
Create the empty array using the identifier "allNames"
Using the push() method, load 4 new objects of names to the array
allNames, populating the fields first , last , age ( data is of
your choosing, for example: allNames.push( new names("Cammo",
"Hammer", 39));
Call printObject, passing the array , sort method as a string (
options are first, last, age, none )
Last line of the script, would be the call to the main
Note: It is required to use the ES6 style of keywords => instead of the older function and for variables use the keyword let, not var, class and within the constructor, not function.
class Names {
constructor(first, last, age) {
this.first = first;
this.last = last;
this.age = age;
}
}
function printObject(allNames, sortType, message) {
if (sortType == "first") {
allNames.sort(function(a, b) {
return a.first.localeCompare(b.first);
});
}
if (sortType == "last") {
allNames.sort(function(a, b) {
return a.last.localeCompare(b.last);
});
}
if (sortType == "age") {
allNames.sort(function(a, b) {
return a.age - b.age;
});
}
for (let i = 0; i < allNames.length; i++) {
console.log(message);
console.log(
allNames[i].first + " " + allNames[i].last + " " + allNames[i].age
);
}
}
function main() {
var allNames = [];
allNames.push(new Names("Cammo", "Hammer", 39));
allNames.push(new Names("Jhon", "Doe", 50));
allNames.push(new Names("Liza", "Helen", 70));
allNames.push(new Names("Anthony", "Jhonson", 30));
allNames.push(new Names("Zakir", "Nayak", 25));
printObject(allNames, "age", "Message");
}
main();