I have an array of objects (student objects which have properties like studentID, grade, dob, registeredDate) and I have another array of objects (books objects which have properties studentID, bookID, bookISBN).
It's a Web app for managing the library at a small school. What I want to do is that when a book (say has title Welcome Home) has been borrowed by student with studentID 4, when you try to lend that book (of course a copy since the library can have a number of them in stock) to someone else, the student with studentID 4 shouldn't be available in the list of students who are eligible to get that book (unless if the student had returned the book first).
The booksList Array is like below:
[
{
bookEdition: "2nd edition",
bookISBN: 9876533278765,
bookStatus: 0,
bookTitle: "Real Machines",
dateTaken: "2018-10-28",
returnDate: "2018-11-27",
studentID: "0000003"
},
{
bookEdition: "2015 edition",
bookISBN: 9876532226712,
bookStatus: 0,
bookTitle: "Real Machines",
dateTaken: "2018-08-28",
returnDate: "2018-09-27",
studentID: "0000004"
}
];
The studentsList is as below:
[
{
bio: "Needs extra work. Has problems with mathematics",
birthday: "2005-05-12",
className: "grade 5",
fullname: "Bridget Friday",
gender: "Female",
parentName: "Josam Friday",
studentID: "0000003",
studentStatus: "approved"
},
{
bio: "A bit naughty but intelligent. Pay close attention to his diet.",
birthday: "2003-11-07",
className: "grade 6",
fullname: "Charles Ben",
gender: "Male",
parentName: "Chris Ben",
studentID: "0000004",
studentStatus: "approved"
}
];
Now, I was trying to use the filter function but it doesn't give me the results I want. The thing that links the two array objects and the objects in them is the studentID.
I tried
var legitStudents = studentsList.filter(el => {
return !booksList.includes(el.studentID);
});
The above doesn't work. The arrays (studentList and booksList) are fetched dynamically and I can't tell which studentIDs are in booksList.
How can I get this to work as I want them?
return !booksList.includes(el.studentID);
should be
return !booksList.map(i => i.studentID).includes(el.studentID);
As a couple people said in the comments of your question, the problem is your code is expecting booksList to be an array of studentIDs. Since it's actually a list of books that have been checked out by students, you first need to make an array of all studentIDs in booksList then you can use includes on the resulting array. See map.
You can use Rocky Sims' solution or you can try this as well
var legitStudents = studentList.filter(student => {
return !booksList.filter(book => book.studentID === student.studentID).length;
});
Related
I have array of objects like this:
var array = [
{
name: "John",
surname: "Doe",
title: "mister"
},
{
name: "Jane",
surname: "Smith",
title: "miss"
},
{
name: "Doe",
surname: "Mustermann",
title: "mister"
}
]
I want to implement a search term through this that will look through multiple properties while sorting them with property priority.
Example: If search term would be Doe, I would like to get this output:
[
{
name: "Doe",
surname: "Mustermann",
title: "mister"
},
{
name: "John",
surname: "Doe",
title: "mister"
}
]
name property has higher priority than surname, that's why hit on name object would go on top.
Filter function only filters through array, but I also would need to move objects up based if search term hit specific field that has higher priority.
I tried implementing this with combination of filter and sort, but unfortunately this was a failure due to both searching through multiple fields in objects, with moving some objects on top depending on which property search was found.
Have a list of fields, ordered by priority:
let fields = ['name', 'surname', 'title']
and then compute the result like this:
let result = fields.flatMap(f => array.filter(x => x[f] === search))
I currently have an array of objects that look like this but with a ton more entries,
[
{
owningrep: "Some name",
id: 1,
emails: "email#address.com;shane#emails.com"
},
{
owningrep: "Other name",
id: 2,
emails: "me#emailstuff.com"
}
]
I also provide the option to import a CSV of emails, which I then take all of the values and put them in an array.
My question is, given this array of objects, and this array of CSV values, how would I then be able to filter the array of objects to NOT include objects where any of the emails in the csv appear in the email value? Keep in mind some objects might have one email, others might have multiple separated by a semicolon.
Thanks in advance
I've attempted to simply filter the array with includes, but that only seems to cut off a few entries.
let inc = inclusionsList.value.length > 0 && inclusionsList.value['0'] != 0 formatDataAsArray(data).filter(d => _.includes(inclusionsList.value, d.id)) : data;
let fromCSV = formatDataAsArray(inc).filter(i => !_.includes(exclusionCSV.value, i.Emails));
Ultimately what I want to do is take an array of objects like:
[
{
owningrep: "Some name",
id: 1,
emails: "email#address.com;shane#emails.com"
},
{
owningrep: "Other name",
id: 2,
emails: "me#emailstuff.com"
}
]
And an array of emails like:
["crona.audreanne#denesik.com", "minerva.leannon#pfannerstill.info", "barton.eloise#yahoo.com", "rachelle.rau#hotmail.com", "ihaley#morar.com", "ggleichner#kirlin.info", "keely.ledner#yahoo.com", "jerel05#yahoo.com", "eleonore35#murphy.info", "ivory56#hotmail.com", "email#address.com"]
And filter the array of objects so that the only objects left are ones whose email key does not include any of the emails in the array.
If I understrand well your problem and your data here is my proposition:
const exclusionCSV = {value: ['mail1', 'me#emailstuff.com']}
const inclusionList = {value: [
{
owningrep: "Some name",
id: 1,
emails: "email#address.com;shane#emails.com"
},
{
owningrep: "Other name",
id: 2,
emails: "me#emailstuff.com"
}
]}
const setExclusionMail = new Set(exclusionCSV.value)
const result = inclusionList.value.filter(({emails}) => {
const mails = emails.split(';')
return !mails.some(m => setExclusionMail.has(m))
})
I've been looking at a problem for hours and failing to find a solution. I'm given an array of customer objects.
In each customer object is an array of friends.
In the array of friends is an object for each friend, containing some data, including a name key/value pair.
What I'm trying to solve for: I'm given this customers array and a customer's name. I need to create a function to find if this customer name is in any other customer's friend lists, and if so, return an array of those customer's names.
Below is a customer list. And as an example, one of the customers is Olga Newton. What the code should be doing is seeing that Olga Newton is a customer and is also in the friends lists of Regina and Jay, and should be returning an array of Regina and Jay.
I thought I could do this simply with a filter function, but because the friends list is an array with more objects, this is adding level of complexity for me I can't figure out.
Below is a customer array. The out put should be
['Regina', 'Jay']
and what I've gotten has either been
[{fullCustomerObj1}, {fullCustomerObj2}]
or
[ ]
What am I missing?
Here is the customer array:
var customers = [{
name: "Olga Newton",
age: 43,
balance: "$3,400",
friends: [{
id: 0,
name: "Justice Lara"
}, {
id: 1,
name: "Duke Patrick"
}, {
id: 2,
name: "Herring Hull"
}, {
id: 3,
name: "Johnnie Berg"
}]
}, {
name: "Regina",
age: 53,
balance: "$4,000",
friends: [{
id: 0,
name: "Cheryl Kent"
}, {
id: 1,
name: "Cynthia Wells"
}, {
id: 2,
name: "Gutierrez Waters"
}, {
id: 3,
name: "Olga Newton"
}]
}, {
name: "Jay",
age: 28,
balance: "$3,000",
friends: [{
id: 0,
name: "Cross Barnett"
}, {
id: 1,
name: "Raquel Haney"
}, {
id: 2,
name: "Olga Newton"
}, {
id: 3,
name: "Shelly Walton"
}]
}];
Use filter and map, please.
function friends(c, name){
return c.filter((a) => {
return a.friends.map(b => b.name).includes(name)
}).map(a => a.name);
}
console.log(friends(customers, "Olga Newton"));
// ['Regina', 'Jay']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
We look to an array (friends[]) inside anther (customers[]), So used two for loops, the first determine witch customer will look for his friends, and the second the array will search inside, then set if statement if the cust name is inside friends[]: adding the customer name to customerFriends[] array, At the end return the customerFriends[].
let cust = "Olga Newton"; // Get the customer name who you look for his friends.
const findFriend = (cust, arrs) => { // Create findFriend function.
let customerFriends = []; // Create an array to set the result to it.
for (let i = 0; i < arrs.length; i++) { // For each Customer.
for (const arr of arrs[i].friends) { // For each Friend.
if (arr.name === cust) { // Use Strict equality to find Customer name in friends[].
customerFriends.push(arrs[i].name); // Add the customer name to the customerFriends[].
}
}
}
return customerFriends;// Return the final results.
}
console.log(findFriend(cust, customers)); // Call the function.
just wondering if someone could point me in the right direction of .map functionality. This is unfortunately something I'm struggling to get my head around.
If I had an object, lets say the following:
const myPetsAndFood = {
pets:[
{
species: "dog",
breed: "Labrador",
age: 12
},
{
species: "cat",
breed: "unknown",
age: 7,
},
{
species: "fish",
breed: "goldfish",
age: 1,
}
],
food: [
{
dogfood: 15.00,
},
{
catfood: 11.00,
},
{
fishfood: 4.00,
}
],
};
Could anyone explain how I'd utilise .map to obtain the data values of age and price if possible please?
A brief explanation or example is more than suffice, I'd appreciate any time/input possible. In all probability, I'll be sat here reading and trying to figure it out in the mean time.
If you got this far - Thank you for your time.
So the .map can only be used with arrays. This way you can not do something similar to:
myPetsAndFood.map()
Let's say you want do console.log the age. You would have to get the array first. So:
myPetsAndFood.pets.map((pet) => {
console.log(pet.age)
})
And it would print 12, followed by 7 followed by 1. If you want to store it inside an array you can create an array and use .push("//infos wanted to be pushed//")
Object.keys(myPetsAndFood).map(function(key, index) {
console.log(myPetsAndFood[key][0].dogfood);
console.log(myPetsAndFood[key][0].age);
});
You are going to have to figure out a way to replace the 0 with some sort of counter that will increment.
map is a method of arrays, it doesn't exist on objects. You could use it on the arrays within the object ( myPetsAndFood.pets.map( /* ... */ ) ) but you'd have to use a for loop or some other technique to parse each item in the object.
An example of how to use the map function for one of your arrays:
const agesArray = myPetsAndFood.pets.map((item) => {
return item.age;
});
So you have imbricated arrays here. This makes it so you have to go into your wanted array first before being able to execute your map.
For example: myPetsAndFood.pets.map(function)
The way that .map works is it executes your function on every element in your array and returns an array with the equivalency(source).
Therefore, in order to get the age of every pet, you have to tell your function to get your age property of your objects.
For example: myPetsAndFood.pets.map((pet) => pet.age)
This will return an array containing only the age of every one of your pets.
Now the problem with this is your second array. We cannot call the .map function on that array because your different properties don't have the same name. Therefore, your .map won't have any common ground to return a sensible array.
We can fix this issue by splitting your one variable into two: name and price for example. After this change, we can now call the .map on your array properly by telling it which property you need.
For example: myPetsAndFood.foods.map((food) => food.price)
Below is a full code snippet which should show off the above description.
const myPetsAndFood = {
pets:[
{
species: "dog",
breed: "Labrador",
age: 12
},
{
species: "cat",
breed: "unknown",
age: 7,
},
{
species: "fish",
breed: "goldfish",
age: 1,
}
],
foods: [
{
name: "dog",
price: 15.00,
},
{
name: "cat",
price: 11.00,
},
{
name: "fish",
price: 4.00,
}
],
};
const catAge = myPetsAndFood.pets.map((pet) => pet.age)
const foodPrice = myPetsAndFood.foods.map((food) => food.price)
console.log(catAge)
console.log(foodPrice)
I'm still learning javascript patterns, and I'm curious about this one.
If I have an array of objects, should I make the array of objects not have keys (Example A), or use their keys (Example B)?
An array of objects without any key:
var soylent_green_candidates = [{
id: 12341,
name: "Don",
gender: "Male",
weapon_of_choice: "Kangaroo Cannon"
},
{
id: 24325,
name: "Jimmy",
gender: "Male",
weapon_of_choice: "Sushi Blaster"
},
...
]
Or an array of objects using the unique ID's as keys:
var soylent_green_candidates = [
12341: {
name: "Don",
gender: "Male",
weapon_of_choice: "Kangaroo Cannon"
},
24325: {
name: "Jimmy",
gender: "Male",
weapon_of_choice: "Sushi Blaster"
},
...
]
Your second example is invalid, so that should put the question to sleep.
In Javascript you have the option of arrays, which are sorted but essentially "key less". Each array entry can only be accessed by its numeric index, period.
The other option is objects, which have no guaranteed order but are keyed by arbitrary values.
['foo', 'bar', 'baz']
{ foo : 'bar', baz : 42 }
You make the choice based on these two criteria, order and requirement for keys.
(Note: while you can use arbitrary numeric indices for arrays, you can't do so using the literal syntax [..], and it's not usually a good idea. If you need explicit keys, you want objects.)