var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
}
How do I convert contacts array to uppercase? After converting the array to uppercase, I want to display the full name in alphabetical order as shown in the picture. Or is there any other way to accomplish without converting to uppercase?
You can use this to convert a string to title casing:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
See example usage:
var nameMixedCaseing = ["alan bong" , "JusTin weasel", "Tom curry"]
for (i = 0; i < nameMixedCaseing.length; i++)
console.log(toTitleCase(nameMixedCaseing[i]));
Result is:
Alan Bong
Justin Weasel
Tom Curry
So in your code you can call this function before saving the person object
person.firstName = toTitleCase(person.firstName);
person.lastName = toTitleCase(person.lastName);
contacts.push(person);
You can use a combination of functions, one to capitalize, one to sort each time a new contact is pushed into the array:
var contacts = [
{
fname: 'andrew',
lname: 'mCGonahan'
},
{
fname: 'paUla',
lname: 'Ptrokva'
},
{
fname: 'kevin',
lname: 'harGRove'
},
{
fname: 'CAmille',
lname: 'dUpoIs'
},
{
fname: 'AlbERt',
lname: 'sWanson'
}
];
function capitalize(arr) {
for (var i = 0; i < arr.length; i++) {
var first = arr[i].fname;
var last = arr[i].lname;
arr[i].fname = first.slice(0,1).toUpperCase() + first.slice(1).toLowerCase();
arr[i].lname = last.slice(0,1).toUpperCase() +last.slice(1).toLowerCase();
}
return arr;
}
function sortByLast(arr) {
return arr.sort(function(a, b) {
if (a.lname > b.lname) return 1;
if (b.lname > a.lname) return -1;
return 0;
});
}
//you can call the following after you have pushed the newest contact into the array
// or you could capitalize the inputs as they are entered, then run the sort function on the contacts array
contacts = sortByLast(capitalize(contacts));
document.getElementById('sortedContacts').innerHTML = JSON.stringify(contacts);
<div id="sortedContacts"><h3></h3></div>
Related
I am trying to check if my array regions contains part of a string that users submit. In essence, this jquery script should check if the city that a user included in their address is one of the cities in the regions array.
For example, when a user enters Examplestreet 24 City1 and City1 is in the regions array, it should display a price of €40, else it should show €2/km.
I have the following code:
var regions = ["city1", "city2", "city3"];
var str = $("#addressField").val();
var address = str.toLowerCase();
var key, value, result;
for (key in regions) {
if (regions.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
value = regions[key];
if (value.substring() === address) {
$("#deliveryPrice").text("€40");
}
else {
$("#deliveryPrice").text("€2/km");
}
}
}
This code is working fine when the string is just the city without the street or other characters, but it should also work if someone enters their full address. So I need to change my code so it searches the array regions for any part of the string address.
You can use regexp to find the right price:
var regions = ["city1", "city2", "city3"];
var address = "example address 42-200 City1 Poland";
var address2 = "city3";
var address3 = "city6";
function priceForAddress(address, regions) {
var city = regions.find(function (region) {
var reg = new RegExp(region, 'i');
return address.match(reg) !== null;
});
if (city) {
return '20$';
} else {
return '4$/km';
}
}
console.log(priceForAddress(address, regions));
console.log(priceForAddress(address2, regions));
console.log(priceForAddress(address3, regions));
You should just find if one of the cities is inside the string using indexOf
function test()
{
var regions = ["city1", "city2", "city3"];
var str = "Examplestreet 24 City1";
var address = str.toLowerCase();
var value, result;
for (value of regions) {
result = str.toLowerCase().indexOf(value);
console.log(result);
if (result !== -1)
{
console.log("$40");
return;
}
else
{
console.log("$2/km");
return;
}
}
}
test();
If I need to see my out put in the page not in console.log i want use document get Element By Id how can i do that? he gave me just one result, Steve only !!
[Code: ]
http://i.stack.imgur.com/ISqzT.png
<script>
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['Microsoft Way']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobes",
number: "(444) 111 000",
address: ["Apple way"]
};
var list = function(obj) {
for( var key in obj){
console.log(obj);
document.getElementById("demo").innerHTML = key + "<br>";
}
}
var search = function(name) {
for(var key in friends){
if(name === friends[key].firstName){
console.log(friends[key]);
}
}
}
list(friends);
// search("Steve");
</script>
Hey the only change you have to make is using += instead of just = for the innerHTML function. Here you go:
text.innerHTML+=friend + "";
Simply append the result to your innerHTML, do not overwrite it, likewise:
document.getElementById("demo").innerHTML += key + "<br>";
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
for(i=0;i<contacts.length;i++){
document.getElementById("mydiv").innerHTML += contacts[i].fname+" "+contacts[i].lname;
}
}
I want to display only the new array elements. In the above code, every time a new element enters the array all elements are displayed. How can I avoid repetition? I think using the DOM is an option. I'm stuck trying to implement this.
You can do it like this, adding only the last element of array to innerHTML
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
document.getElementById("mydiv").innerHTML += contacts[contacts.length-1].fname+" "+contacts[contacts.length-1].lname;
}
Before you add all the elements you have to empty your div.
document.getElementById("mydiv").innerHTML = ''
Here is a working snippet of what you asked. you just have to take the last pushed object from the array and display the names.
Also your var fname, lname, email, phone is not required, You can set the object properties on the fly.
var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
// var fname, lname, email, phone; //also this is not required. you can set dynamic property names in a object.
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
};
contacts.push(person);
var currPerson = contacts[contacts.length-1]; //take the last pushed object from the array
var lastNameFirstChar = currPerson.lname.charAt(0).toUpperCase();
if(!document.getElementById(lastNameFirstChar + "_holder")){
document.getElementById("mydiv").innerHTML += "<div id='"+lastNameFirstChar+"_holder' class='holder'><span class='charValue'>"+lastNameFirstChar+"</span></br></div>";
}
document.getElementById(lastNameFirstChar + "_holder").innerHTML += currPerson.fname+" "+currPerson.lname + "<br/>";
}
<button onclick="getInfo()">Get Person Info</button>
<p>----------------------------</p>
<div id="mydiv">
</div>
EDIT: Since you said you can use Jquery I have updated the solution with Jquery.
just change:
if(contacts.length!=0){
document.getElementById("mydiv").innerHTML += contacts[contacts.length-1].fname+" "+contacts[contacts.length-1].lname;
}
The if check is for the start when length of array is zero
Thanks for having a look at my question! I'm trying to complete the JavaScript course in codecademy and this has me stumped. I can't even find help in the codecademy forums. I am trying to figure out why "Bob Jones" isn't logged to the console. Any help is greatly appreciated. Here is my code:
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones#example.com"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson#example.com"
};
var contacts = [bob, mary];
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
};
function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
};
/*Create a search function
then call it passing "Jones"*/
function search(lastName){
var contactsLength = contacts.Length;
for(var i = 0; i<contactsLength; i++){
if(lastName === contacts[i].lastName){
printPerson(contacts[i]);
}
}
};
search("Jones");
The problem is that JavaScript is case sensitive and the array length is available under the lengthproperty, not Length.
P.S. learn to use a debugger.
I'm building an array dynamically in a test angular app. Basically I have a scope function that generates an array of people and returns the array and I have an ng-repeat on the array. The array is not displaying but I'm not getting any errors in the console either, so idk what's up:
am I calling the getPerson function correctly? If there's a better way to do this do let me know.
heres the fiddle as well
$scope.person = {
firstname: "",
lastname: "",
isActive: true,
fullname: function() {
var personobject;
personobject = $scope.person;
return personobject.firstname
+ " "
+ personobject.lastname;
}
};
$scope.people = function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
};
$scope.getPerson = function(first, last, active) {
var newPerson = $scope.person;
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
I've updated your fiddle here : https://jsfiddle.net/7j2khgbj/2/
var myapp = angular.module("myapp", []);
myapp.controller('appCont', function($scope) {
var Person = function(){
this.firstname = "";
this.lastname = "";
this.isActive = true;
};
Person.prototype.fullname = function() {
return this.firstname
+ " "
+ this.lastname;
};
var getPerson = function(first, last, active) {
var newPerson = new Person();
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
$scope.addPerson = function() {
$scope.people.push({
firstname: $scope.person.firstname,
lastname: $scope.person.lastname
});
$scope.person.firstname = '';
$scope.person.lastname = '';
};
$scope.people = (function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
})();
/*$scope.people = [
{firstname: 'abdul', lastname: 'ahmad'},
{firstname: 'mahmud', lastname: 'samrai'},
{firstname: 'gasser', lastname: 'badawi'},
{firstname: 'ibtihaj', lastname: 'jasim'},
{firstname: 'abudi', lastname: 'ahmad'},
{firstname: 'ahmad', lastname: 'jasim'},
{firstname: 'abdul', lastname: 'samrai'}
];*/
});
Some problems I saw:
1) $scope.people was a function, not an array (so I simply executed it and saved the result)
2) you were always overwriting the person (you need a Person class that creates new instances for the array element, not overwrite the same instance with new data - that way you'll get the same thing in all the array elements)
3) on $scope you should put things that need to be accessible from the view. Helper functions can just be local in the controller (if you don't want them as services, although as services they are reusable)
4) track by on ng-repeat (in case of duplicate keys)