how to make multi dimensional array with for loop? - javascript

FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i=0 ;i<10;i++){
contacts[i] = [];
for(c=0;c<3;c++){
contacts[i].push(FirstName);
contacts[i].push(LastName);
contacts[i].push(Adress);
}
}
the code gives me the contacts array with 10 arrays and each array has the information repeated 3times

You don't need the second for loop:
FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
contacts[i] = [];
contacts[i].push(FirstName);
contacts[i].push(LastName);
contacts[i].push(Adress);
}
Or you can also use this way:
FirstName = FirstName.value;
LastName = LastName.value;
Adress = Adress.value;
for(i = 0; i < 10; i++) {
contacts[i] = [FirstName, LastName, Adress];
}

I am not sure on the objective but I think you should be using objects to store your information instead of 2D arrays.
(Jsfiddle that show 2d array and array with objects). So instead of
var contacts = [
['John', 'Doe', '100 Main Street'],
['Jane','Smith','101 Main']
];
you would have
var contacts = [
{
first_name: 'John',
last_name: 'Doe',
address: '100 Main Street'
},
{
first_name: 'Jane',
last_name: 'Smith',
address: '101 Main Street'
}
];
Try this. It will push the form name and email onto the contacts
<form onsubmit='formSubmit(event);'>
<label>name</label>
<input id='name' value='John'/>
<label>email</label>
<input id='email' value='fake#test.com'/>
<br/>
<button>
add name and email
</button>
</form>
function formSubmit(event){
event.preventDefault();
contacts.push({
name: document.getElementById('name').value,
email: document.getElementById('email').value
})
console.log(contacts);
}

Related

How to remove an object from an array if it has the letter a?

I need to make a function that receives 2 parameters, the first one is an array of a list of users that must contain first name, last name and phone numbers, at least 3 of those users must start with the letter "a", the second parameter is a callback. You must process the array and delete all the users whose name starts with the letter "a". Then send the new processed array to the callback. The callback must show in console, the list of all the names, concatenating first and last name.
const users =
[{
name: 'Diego',
lastname: 'Garcia',
phone: '12343'
},
{
name: 'Camilo',
lastname: 'Garcia',
phone: '12343'
}, {
name: 'ana',
lastname: 'Rodriguez',
phone: '02343'
}, {
name: 'anastasia',
lastname: 'Zapata',
phone: '42343'
}, {
name: 'alejandra',
lastname: 'Perez',
phone: '52343'
}];
const operation2 = (list) => {
let x = [];
let callback = {};
callback = list.find(element => element.name.charAt(0) == 'a');
let l = list.indexOf(callback)
let g = list[l];
console.log(g)
if (callback) {
x = list.splice(l, 1)
} return list
}
console.log(operation2(users))
The code that I made does not work, it is not eliminating all the names that begin with "a", it only eliminates the first object of the array.
Array.find only finds the first match, you should probably filter out the elements you don't want:
const result = list.filter(element => element.name.charAt(0) !== 'a');
const users =
[{
name: 'Diego',
lastname: 'Garcia',
phone: '12343'
},
{
name: 'Camilo',
lastname: 'Garcia',
phone: '12343'
}, {
name: 'ana',
lastname: 'Rodriguez',
phone: '02343'
}, {
name: 'anastasia',
lastname: 'Zapata',
phone: '42343'
}, {
name: 'alejandra',
lastname: 'Perez',
phone: '52343'
}];
function func(list, callback) {
let users = list.filter(u => !u.name.toLowerCase().startsWith('a'));
callback(users)
}
func(users, (users) => {
console.log(users)
})

How do I add content to html body using JavaScript?

when a given array includes a list of employees
let names = [
{ firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
{ firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];
and #ul is already provided,
<ul id="container">
<li>
<a class="name">John Doe</a>
<div class="age">41</div>
</li>
<li>
<a class="name">Mary Jane</a>
<div class="age">20</div>
</li>
</ul>
I need to return a role of an employee when employee's name is clicked. here is my code
function findRoles(array) {
const container = document.getElementById('container');
for (let i = 0; i < array.length; i++) {
const li = document.createElement('li'),
a = document.createElement('a'),
div = document.createElement('div');
ul = document.createElement('ul');
let user = array[i];
a.innerText = user.firstName + ' ' + user.lastName;
a.className = 'name';
a.addEventListener("click", () => printRole(user))
//div.className = "age";
li.appendChild(a);
li.appendChild(div);
container.appendChild(li);
}
}
which results this following error :
AssertionError: expected '<a class="name"></a>' to equal '<a class="name">John Doe</a>'
It appears contents of <a class="name"> is missing.
been working on this for the past 4 hours and don't seem to figure it out
Your code seems working in snippet. Just added the printRole method.
function printRole(usr) {
console.log('Clicked on user: ', `${usr.firstName} ${usr.lastName}`, '; Role is ', usr.role);
}
function findRoles(array) {
const container = document.getElementById('container');
for (let i = 0; i < array.length; i++) {
const li = document.createElement('li'),
a = document.createElement('a'),
div = document.createElement('div');
ul = document.createElement('ul');
let user = array[i];
a.innerText = user.firstName + ' ' + user.lastName;
a.className = 'name';
a.addEventListener("click", () => printRole(user))
//div.className = "age";
li.appendChild(a);
li.appendChild(div);
container.appendChild(li);
}
}
let names = [
{ firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
{ firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];
findRoles(names)
<div id="container"> </div>
I had to completely change the logic of your js code.
Was it necessary?
let names = [
{ firstName: 'John', lastName: 'Doe', DOB: '01Jan1970', role: 'cook' },
{ firstName: 'Mary', lastName: 'Jane', DOB: '11Sep2000', role: 'server' },
];
let name_mans = document.querySelectorAll('.name');
Array.from(name_mans).forEach(function(name_man, i) {
name_man.addEventListener('click', function() {
console.log(names[i].role);
});
});
<ul id="container">
<li>
<a class="name">John Doe</a>
<div class="age">41</div>
</li>
<li>
<a class="name">Mary Jane</a>
<div class="age">20</div>
</li>
</ul>

store user input in an array and display on screen

Storing info in an array(firstName, lastName, accNumber, etc). I already have some data in array. I want to ask user input and push that input in array and save it as well as display it on screen(not in console). Also new info is not saving in the array. I use prompt as well as form . from is not working.
/* creatting array */
var customer = [
{fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
{fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
{fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
];
console.log(customer.length);
console.log(customer[1].fname);
console.log(customer[2].lname);
var newName = prompt("what is your lnamename?");
customer.push(newName);
console.log(customer);
/*function to add data in array*/
function addInArray() {
var addName = document.getElementById("#nameInput");
customer.push(addName.value);
addName.value = "";
console.log(customer);
}
/* display array*/
function displayArray(){
for(var i=0; i < customer.lenght; i++){
document.write("customer" + i + customer[i] + "</br>");
document.getElementById("#showName").innerHTML = customer[i];
}
}
</script>
<form>
<input id="nameInput" type="text"/ placeholder="yourInfo">
<button type="button" id="add" onclick="addInArray();">Add </button>
<button type="button" id="myList" onclick="displayArray();">Display</button>
</form>
<div id="box"></div>
<div id="showName"> </div>
</body>
You shouldn't write # while you are using getElementById
/* creatting array */
var customer = [
{fname: "Jhon", lname: "Yojin", accNo: 1, balance: 400},
{fname: "Jane", lname: "Jin", accNo: 2, balance: 500},
{fname: "Emily", lname: "Sena", accNo: 5, balance: 100}
];
displayMyAcc()
function displayMyAcc(){
var myAccNo = prompt("what is your acc number?");
document.getElementById("showName").innerHTML=JSON.stringify(customer.filter(x=>x.accNo==myAccNo)[0]);
}
/*function to add data in array*/
function addInArray() {
var addName = document.getElementById("nameInput");
customer.push(addName.value);
addName.value = "";
}
/* display array*/
function displayArray(){
for(var i=0; i < customer.length; i++){
document.getElementById("showName").innerHTML += JSON.stringify(customer[i]);
}
}
<form>
<input id="nameInput" type="text"/ placeholder="yourInfo">
<button type="button" id="add" onclick="addInArray();">Add </button>
<button type="button" id="myList" onclick="displayArray();">Display</button>
</form>
<div id="box"></div>
<div id="showName"> </div>

how to make a new div with jquery?

okay so, I need to create a new div using jquery with the information of a first and last name that I loop from my array.. This is what I have so far, I was wondering if I could get some help on how to make it show up on my webpage. it needs to show up like:
hello firstname lastname
hello firstname lastname
hello firstname lastname
<div id="output"></div>
function names() {
var firstAndLast = [
{name: "jane", surname: "doe"},
{name: "john", surname: "leg"},
{name: "hunny", surname: "bun"}
];
var div = $("#output");
for (var i=0; i < firstAndLast.length; i++) {
}
var div1 = $("<div>").html("Hello name surname");
$("#names").append(div1);
Your code is almost there. The main issue is that you need to put the line of jQuery which creates the div and appends it within the for loop. In addition you can retrieve the name and surname from the objects in the array using the i variable to access them by index:
var $output = $("#output");
for (var i = 0; i < firstAndLast.length; i++) {
var div1 = $("<div>").html(`Hello ${firstAndLast[i].name} ${firstAndLast[i].surname}`);
$output.append(div1);
}
That being said, the most performant way to do this would be to use map() to build an array of HTML strings which you only append to the DOM once:
function names() {
let firstAndLast = [
{ name: "jane", surname: "doe" },
{ name: "john", surname: "leg" },
{ name: "hunny", surname: "bun" }
];
let html = firstAndLast.map(o => `<div>Hello ${o.name} ${o.surname}</div>`);
$("#output").append(html);
}
names();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
You can try something like this
function names() {
var firstAndLast = [{
name: "jane",
surname: "doe"
},
{
name: "john",
surname: "leg"
},
{
name: "hunny",
surname: "bun"
}
];
let _data = firstAndLast.reduce((acc, {
name,
surname
}) => {
acc += `hello <span>${name}</span> <span>${surname}</span><br>`
return acc;
}, "")
$("#output").html(_data);
}
names()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>

Iterating through object properties/keys

I'm just starting to learn coding, and i came across this question that i could not understand.
"The second function we'll add will be called search, and it will take a first name as an argument. It will try to match the first name it receives to any of the first names in our friends contact list. If it finds a match, it will log our friend's contact information (firstName, lastName, number, address) to the console."
variables are define as follows :
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
the answer is as follows :
var search = function(name) {
for(var key in friends) {
if(friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
could someone better explain how did the var "key" came about ? and why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
would appreciate if someone could explain thank you.
From OP's comment:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
friends is a nested object which can also be represented like so:
friends = {
bill: {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
},
steve: {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
}
}
The for..in loop iterates over all keys in the friends object, with the variable key in your case.
why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
Because, to do that, you need to have firstName or name as a property in friends. Since those properties are nested inside (name is not event inside the nested objects), there was a for..in loop used.
You have an object friends that has 2 properties bill and steve (those are the keys). Calling friends.bill will return you an object (the value) with firstname, lastname, number, address. You need to iterate all the properties of your object friends to find the one you need
You can use Object.values(obj)
var firstNameInput = "Steve";
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
//Iterates all the friends
Object.values(friends).forEach(function(f){
//Compare the property "firstname" with the input
if(f.firstName === firstNameInput){
//Friend found
console.log(f);
return;
}
});

Categories

Resources