'java script function for filling a list
I wrote a function that enters personal information into empty list and save them. I want to add one by one but if first name and last name have entered before, show me "user has been added before" and does not add repeated user.my function does not work and i do not understand why? list is still empty!!
var personalInfo = [];
function addEmployee(firstName, lastName, hourPerMonth, salaryPerHour) {
if (hourPerMonth > 160) return 'hourPerMonth is too much';
personalInfo.push({
'firstName': firstName,
'lastName': lastName,
'hourPerMonth': hourPerMonth,
'salaryPerHour': salaryPerHour
});
for (let index = 0; index < personalInfo.length; index++) {
let item = personalInfo[index];
if (item.firstName !== firstName && item.lastName !== lastName) {
personalInfo.push({
'firstName': firstName,
'lastName': lastName,
'hourPerMonth': hourPerMonth,
'salaryPerHour': salaryPerHour
});
}
}
return personalInfo;
}
//for example:
addEmployee('alex', 'ortemi', 134, 23); //ok
addEmployee('olivia', 'zikari', 144, 26); //ok
addEmployee('alex', 'ortemi', 132, 13); // error : user has been added before
any solution would be my appreciate
I have tried couple of solutions but i did not get answer
Solution 1:[1]
This should do
let personalInfo = [];
//adds user to DB
const addEmployee = (
firstName,
lastName,
workHoursPerMonth,
salaryPerHour,
dataBase = personalInfo
) => {
let isDuplicate = false;
/*loop over the DB to check if firstName and lastName comb. has a duplicate*/
for (let i = 0; i < dataBase.length; i++) {
// check if the input firstName and lastName combination match dataBase[i] element
if (
workHoursPerMonth < 160 &&
(dataBase.length === 0 ||
!(
dataBase[i].firstName === firstName &&
dataBase[i].lastName === lastName
))
) {
} else {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
dataBase.push({});
dataBase[dataBase.length - 1].firstName = firstName;
dataBase[dataBase.length - 1].lastName = lastName;
dataBase[dataBase.length - 1].workHoursPerMonth = workHoursPerMonth;
dataBase[dataBase.length - 1].salaryPerHour = salaryPerHour;
isDuplicate = true;
return `user '${firstName} ${lastName}' was successfully added.`;
} else {
return `We couldn't Add user: '${firstName} ${lastName}' ! perhaps cause of duplicated data or irregular work hour`;
}
};
addEmployee("alex", "ortemi", 134, 23); //ok
addEmployee("olivia", "zikari", 144, 26); //ok
addEmployee("alex", "ortemi", 132, 13); // the function filters that succesfully
console.log(personalInfo);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hootan |
