This is the image of the array named database I am using
I don't know how to use the forEach loop properly, can someone say why this does not work?
This is what I tried.
var database = [{
username: 'gaurav',
password: 'password'
}, {
username: 'gaurav1',
password: 'password1'
}, {
username: 'gaurav2',
password: 'password2'
}];
database.forEach(credential => {// credential is the object = {username, password}
if (credential.username === credential.username && credential.password === credential.password) {
console.log('matched');
}
})
forEach will expect function having array of objects as "database" is having collection of objects. So we cannot have 2 separate parameters as you are passing "function (username, password)". It should be function(obj).
The reason your forEach loop doesn't work is that you are passing it a function that looks like this:
function f(user, password) {
password == 'examplepassword';
user == 'someuser';
}
Your function is taking the wrong parameters. forEach goes over an array, and passes each item of the array to the function you are giving it. The function should be instead written like:
function f(item) {
item.password == 'examplepassword';
item.user == 'someuser';
}
So you would want to rewrite your code to be more like
db = [{username: 'a', password: 'abc'}, {username: 'b', password: 'bca'}]
db.forEach(function(user) {
console.log("user " + user.username + " has password " + user.password);
})
/* Output:
user a has password abc
user b has password bca
*/
Extra credit:
You can find more details in the documentation for forEach. The function you pass forEach can also have two other arguments, the nÂș of the item it is currently passed, and the original array.
let a = ['a', 'b', 'c']
function f(item, position, array) {
console.log("The letter " + item + " is in position " + position)
console.log("array[position] == " + array[position])
}
a.forEach(f);
/* Output:
The letter a is in position 0
array[position] == a
The letter b is in position 1
array[position] == b
The letter c is in position 2
array[position] == c
*/
Related
I am trying to create ONE string from an array of objects family and have them separated by commas except for the last element Mary
const family = [
{Person: {
name: John
}}, {Person: {
name: Mike
}}, {Person: {
name: Link
}}
, {Person: {
name: Mary
}}];
I want the string to be like this
"John, Mike, Link or Mary"
I tried using family.toString() but that gives me "John, Mike, Link, Mary" and doesn't allow me to replace "," with an "OR"
Use pop() to get (and remove) the last name. Then use join() to add the rest.
Thx to #charlietfl for suggesting a check on the number of names to prevent something like: and John.
const family = [
{ Person: { name: "John" } },
{ Person: { name: "Mike" } },
{ Person: { name: "Link" } },
{ Person: { name: "Mary" } }
];
// Get all the names
const names = family.map((x) => x.Person.name);
// Get result based on number of names
let result = '';
if (names.length === 1) {
// Just show the single name
result = names[0];
} else {
// Get last name
const lastName = names.pop();
// Create result
result = names.join(', ') + ' and ' + lastName;
}
// Show output
console.log(result);
I don't think there's a super-elogant option. Best bet is something like:
function joinWord(arr, sep, finalsep) {
return arr.slice(0,-1).join(sep) + finalsep + arr[arr.length-1];
}
and then
joinWord(family.map(x=>x.person.name), ', ', ' or ');
You could make the invocation a little nicer at the cost of performance and modularity with:
Array.prototype.joinWord = function joinWord(sep, finalsep) {
return this.slice(0,-1).join(sep) + finalsep + this[this.length-1];
}
family.map(x=>x.person.name).joinWord(', ', ' or ')
But this is only a good idea if this is going to come up a lot within your program and your program is never going to be a part of something bigger. It effects every array.
How about
let sp = ' or ';
family.map(x => x.Person.name)
.reduceRight(
(x,y) => {
const r = sp + y + x;
sp = ', ';
return r;
}, '')
.replace(', ', '');
Hope, this question was for the school homework :)
I have a simple function that checks if the username already exists in the array of objects, in case it does, it should save new time in an array in format { username: username, time: [firsttime, secondtime, etc] }. The code itself is rough, but the problem is that if the username doesn't exist (and the array is not empty, so there are some other usernames saved already), the function saves the time two times, if I try the same username, I get one more object with double time.
let array = []
const userName = prompt("username")
const userTime = prompt("points")
if (array.length > 0) {
for (let i = 0; i < array.length; i++) {
if (array[i].username === userName) {
array[i].time.push(userTime)
} else {
const thisTime = {
username: userName,
time: [userTime]
}
array.push(thisTime)
}
}
} else {
const firstTime = {
username: userName,
time: [userTime]
}
array.push(firstTime)
console.log(array)
}
So on the first round i get [{username: "maria", time: Array(1)}]
On the second round with another username [{username: "maria", time: Array(1)}, {username: "ariana", time: Array(2) e.g. [14,14] (should be only 1 value)}]
The code was edited according to the rules, so actual username and time are added in course of the game.
You could do that with a more efficient and less error prone way:
// look for the index in the array
const pointIndex = this.points.findIndex(point => point.username === this.username);
if(pointIndex > -1){ // if found, push the time
this.points[pointIndex].time.push(this.globalTime);
}
else { // push a new point otherwise
const thisTime = {
username: this.username,
time: [this.globalTime]
}
this.points.push(thisTime)
}
I have an array with 50 users. So then i've a method add:(should accept object of user (field firstName is required), add it to array of users, (user id for new user should be generated programmatically and be unique))
const users = [{
"id": 1,
"first_name": "Abner",
"last_name": "Glaisner",
"gender": "Male",
"language": "Tswana"
}, {
//...
}]
class UserList {
constructor(users) {
this.users = users;
}
add(newUser) {
if (typeof newUser === 'object' && typeof newUser !== null) {
users.push(newUser);
newUser.id = users.length;
console.log(`Hello everyone i am ${newUser.first_name}`);
} else {
console.log('Please add object where first_name field is required!');
}
}
}
So what i need is when user writes
UserList.add({
first_name: 'Jack',
last_name: 'Nollan',
//...
})
Make him to fill first_name.
Is it possible to do ?
And also i use newUser.id = user.length to generate user's id, is it possible to push it at the begining of object not to the end of it ?
Answering your second question; You could achieve it by using the array spread operator you could do something like this:
users = [newUser, ...users];
Note that this overwrites the array every time you add something to it.
Another approach would be to Array.reverse it where you use it.
You should also check for new user's first and last name as they are required.
i.e: && newUser.first_name && newUser.last_name.
You can simply
if(newUser && typeOf newUser === "object" && newUser.first_name && newUser.last_name){
//add to []
}else {
//show message code
}
You already have an if block to check if it's a valid user, why not use it to check if first_name is set?
As for adding an object at the beginning of an array, you could use the expand operator for that. ([newElement, ...array])
class UserList {
constructor(users) {
this.users = users;
}
add(newUser) {
if (typeof newUser === 'object' && newUser.first_name) {
users = [{id: users.length, ...newUser}, ...users];
console.log(`Hello everyone i am ${newUser.first_name}`);
} else {
console.log('Please add object where first_name field is required!');
}
}
}
EDIT:
As Linschlager was quick to point out, you can even make it a one-liner by creating a new object from id: users.length and expanding the newUser object.
Im having some trouble figuring this out. I have a database which has users on it and I want to display each user on the page dynamically using jquery.
Ive just thrown some user data objects in a array and im trying to call for each user object in the array to display as a list item on the page
html
<h1>List</h1>
<ul id="list">
</ul>
javascript
var user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
]
function addUser() {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user + " " + $age);
}
$.each(user, addUser());
Your mistake is very simple. You have to replace addUser() by addUser when you use the $.each method. There are also mistakes when you use the.append method. Try this code:
var user = [
{
username: "alex",
age: 20
},
{
username: "james",
age: 20
}
];
function addUser(theCase, value) {
var username = value.username;
var age = value.age;
var user = '<li> ' + username; // Use a simple string, it's better and faster!
var age = age + ' </li>';
$("#list").append(user + " " + age);
}
$.each(user, addUser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<h1>List</h1>
<ul id="list">
</ul>
Here you are using a callback. If you want more details about callbacks consult the MDN's documentation.
There are also several errors on .each method or .append method. Consult the documentation.
The .each method call your callback for each case on your array user. This method also provide you, in your callback, the index and the value of the case witch is treated.
Can you please check page: https://jsfiddle.net/rxcz73x9/2/
var user = [{
username: "alex", // use string
age: 20
}, {
username: "james", // use string
age: 20
}];
function addUser(idx, user) {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user).append($age); // use append for each node
}
$.each(user, addUser); // use function name instead of addUser()
I've added comment that could help you with example above.
When you pass a callback to the jQuery each function, what happens is that the callback is going to be invoked with every element in your user array.
Check the arguments that jQuery.each passes to the callback. The callback function signature should expect the index and the value of the element in that index.
For example:
var users = user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
];
function addUser(index, user) {
// do what you want and in the end
$('#list').append(/* an <li> element */);
};
// Now pass the function as a callback, but don't invoke it.
$.each(users, addUser);
So the "for var x in friends" loop is going to search each key inside friends, which would be bill and steve, and then with "friends[x].firstName === name" we are checking if the first name is equal to "name", but how does the program know if "name" is Steve or Bill? I'm missing something here.
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: " ",
address: [' ', ' ', ' ',' ']
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: " ",
address: [' ', ' ', ' ',' ']
}
};
var list = function(friends) {
for (var x in friends) {
console.log(x);
}
};
var search = function(name) {
for (var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
for (var x in friends)
This iteates over all keys in friends, resulting in two loop iterations with
x = "bill"
x = "steve"
Then with friends[x] in the loop you access friends.bill and freinds.steve.
The name variable is given as a parameter to search(name). This effectivly searches all entries in the dict friends for firstName == name.
here we have defined search as a function search which accepts an argument name .
var search = function(name)
and we use the function like
search('Bill')
So the function knows which name we are looking for, which is Bill . It will iterate through each item and compare each firstName with Bill. It returns the corresponding friends[x] , when it finds a match .
The advantage of function with parameter is that, with the same function we can search for any name . ex : search('Steve') , search('Bill') .
if you don't understand functions with parameters, revisit the codeacademy section understanding parameters - js