So I'm working on a problem that I've been staring at for far too long. I have an array of people, each represented by an object. Inside each person object is a value for friends, which is an array.
The friends array contains an object for each friend, with one of the key/value pairs being name: 'name'.
I need to find how many friends of a given person have names that start with given letter.
Below is the array of people, including the friends array for each person. After that is the code I've worked with out so far, trying to use reduce.
var customers = [{
name: "Courtney",
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: "Greta Wells"
}, {
id: 2,
name: "Gutierrez Waters"
}, {
id: 3,
name: "Cooley Jimenez"
}]
}, {
name: "Jay",
age: 28,
balance: "$3,000",
friends: [{
id: 0,
name: "Cross Barnett"
}, {
id: 1,
name: "Raquel Haney"
}, {
id: 2,
name: "Cassandra Martin"
}, {
id: 3,
name: "Shelly Walton"
}]
}];
var friendFirstLetterCount = function(array, customer, letter) {
let friendNames = [];
for (let i = 0; i < customer.friends.length; i ) {
friendNames.push(customer.friends[i].name);
}
let friendCount = _.filter(friendNames, function(current, index, array) {
return current.toLowerCase().charAt(0) === letter.toLowerCase();
});
return friendCount.length;
};
CodePudding user response:
This seems to work. Read the inline comments for an explanation of how:
function friendFirstLetterCount(array, customer, letter) {
// Find the customer object in the array, where the customer name is equal to customer.
const customerObj = array.filter(arrayCustomer => arrayCustomer.name === customer)[0];
// Return zero if customer not found.
// (Up to you how you handle this, you might want an exception instead).
if (!customerObj) return 0;
// Find all customer friends whose name starts with letter and return the length.
return customerObj.friends.filter(friend => friend.name.startsWith(letter)).length;
}
Test run
friendFirstLetterCount(customers, "Regina", "C");
Result
2
There are likely a few edge cases you want to watch out for; for example, what happens if the customer isn't found (see comments), and what happens if the customer doesn't have any friends.
Edit: I also think it's more readable with the following parameter and variable names
function friendFirstLetterCount(array, name, letter) {
// Find the customer object in the array, where the customer name is equal to customer.
const customer = array.filter(customer => customer.name === name)[0];
// Return zero if customer not found.
if (!customer) return 0;
// Find all customer friends whose name starts with letter and return the length.
return customer.friends.filter(friend => friend.name.startsWith(letter)).length;
}
CodePudding user response:
i didn't achieve it exaclty but i think this could be a really clean solution :
var matches = [];
customers.forEach((cus) => {
matches[cus.name] = cus.friends.filter(function(friend)
{
let friends = friend.name.startsWith('C');
return friends;
})
});
like this `
0:[]
1:[]
2:[{...}]
0:(2) {id: 3, name: "Shelly Walton"}`
it returns you a list of the matching friends for each customer, you can tweak it to get something like 'customerName': []
edited with the cus.name and .length :
var matches = [];
customers.forEach((cus) => {
matches[cus.name] = cus.friends.filter(function(friend)
{
let friends = friend.name.startsWith('C');
return friends;
}).length
});
you will get [ Courtney: 0, Regina: 2, Jay: 2 ]
as a result
CodePudding user response:
var customers = [{
name: "Courtney",
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: "Greta Wells"
}, {
id: 2,
name: "Gutierrez Waters"
}, {
id: 3,
name: "Cooley Jimenez"
}]
},
{
name: "Jay",
age: 28,
balance: "$3,000",
friends: [{
id: 0,
name: "Cross Barnett"
}, {
id: 1,
name: "Raquel Haney"
}, {
id: 2,
name: "Cassandra Martin"
}, {
id: 3,
name: "Shelly Walton"
}]
}
]
var friendFirstLetterCount = function(array, customerName, letter) {
const customerObj = array.find(customer => customer.name.toLowerCase() === customerName.toLowerCase());
let friendNames = customerObj.friends;
let friendCount = friendNames.filter(friend => friend.name.toLowerCase().startsWith(letter.toLowerCase()));
return friendCount.length;
};
const count = friendFirstLetterCount(customers, 'Regina', 'c');
console.log(count)
CodePudding user response:
Doing it very functionally, here are two functions that do logical chunks of the work...
// get the first letter of every name in an object's fiends array
const friendsInitials = object => object.friends.map(el => el.name[0]);
// count the number of times a letter appears in an array of letters
const count = (array, letter) => array.filter(el => el === letter).length;
With those, we can write a function that does what we want for an input object...
// count the number of times letter is the first letter of the friends' names
const initialCount = (object, letter) => count(friendsInitials(object), letter);
And run it like this...
// get an array of counts by mapping the initialCount over the input
const customers = [ /* OP customers array */ ];
const letter = "C";
const firstInitialCounts = customers.map(c => initialCount(c, letter));
Demo...
// get the first letter of every name in an object's fiends array
const friendsInitials = object => object.friends.map(el => el.name[0]);
// count the number of times letter appears in an array of letters
const count = (array, letter) => array.filter(el => el === letter).length;
// count the number of times letter is the first letter of the friends' names
const initialCount = (object, letter) => count(friendsInitials(object), letter);
// get an array of counts by mapping the initialCount over the input
const customers = [{
name: "Courtney",
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: "Greta Wells"
}, {
id: 2,
name: "Gutierrez Waters"
}, {
id: 3,
name: "Cooley Jimenez"
}]
}, {
name: "Jay",
age: 28,
balance: "$3,000",
friends: [{
id: 0,
name: "Cross Barnett"
}, {
id: 1,
name: "Raquel Haney"
}, {
id: 2,
name: "Cassandra Martin"
}, {
id: 3,
name: "Shelly Walton"
}]
}];
const letter = "C";
const firstInitialCounts = customers.map(c => initialCount(c, letter));
console.log(firstInitialCounts)
CodePudding user response:
3 Parameters
- Array of objects - (
cutomers
) - String - The name of a
customer.name
(name
) - String - The letter that the
friend.name
s must start with (letter
).
Steps
.flatMap()
customers
array.- Compare
customer.name
with thename
parametercustomer.name.toLowerCase().includes(name.toLowerCase())
- Once found,
.flatMap()
oncustomer.friends
array - Compare
friend.name
with theletter
parameter.true
returns a 1 otherwise 0 is returned.if(friend.name.toLowerCase().charAt(0) === letter.toLowerCase()) { return 1; } else { return 0; }
- Next the returned array is
.filtered(a => a)
for "" and then.reduce()
to a sum.
const customers =[{name:"Courtney",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:"Greta Wells"},{id:2,name:"Gutierrez Waters"},{id:3,name:"Cooley Jimenez"}]},{name:"Jay",age:28,balance:"$3,000",friends:[{id:0,name:"Cross Barnett"},{id:1,name:"Raquel Haney"},{id:2,name:"Cassandra Martin"},{id:3,name:"Shelly Walton"}]}];
function findFriend(array, name, letter) {
const result = array
.flatMap((customer) => {
//console.log(customer.name.toLowerCase());
if (customer.name.toLowerCase().includes(name.toLowerCase())) {
//console.log(customer.friends)
return customer.friends.flatMap((friend) => {
//console.log(friend.name)
if (friend.name.toLowerCase().charAt(0) === letter.toLowerCase()) {
return 1;
} else {
return 0;
}
});
}
})
.filter((a) => a);
//console.log(result)
return result.reduce((sum, add) => sum add);
}
console.log("Courtney has " findFriend(customers, "courtney", "j") " friends whose names starts with a 'J'");
console.log("Regina has " findFriend(customers, "regina", "g") " friends whose names starts with a 'G'");
console.log("Jay has " findFriend(customers, "jay", "c") " friends whose names starts with a 'C'");