When typing in 'John Smith' for example, slice removes the first two employee names instead of only John's. Any idea why this is happening?
let removeEmployee = '';
let employees = [
{
name: 'John Smith'
}, {
name: 'Jackie Jackson'
}, {
name: 'Chris Jones'
}, {
name: 'Amanda Cullen'
}, {
name: 'Jeremy Goodwin'
}, ]
removeEmployee = prompt('Enter the name of the employee to be removed:');
function employeeExists(employee) {
return employees.some(function(el) {
return el.name === employee;
});
}
if (employeeExists(removeEmployee)) {
employees.forEach(function(employee, index, object) {
if (employee.name === removeEmployee) {
object.splice(index, 1);
} else {
console.log(employee.name);
}
});
} else {
console.log('That employee does not exist, please try again.');
}
You could make things a little simpler using filter instead of forEach:
if (employeeExists(removeEmployee)) {
employees = employees.filter(e => e.name !== removeEmployee);
}
If you still want to use splice, you could use findIndex with it:
let employees = [ {name: 'John Smith'}, {name: 'Jackie Jackson'}, {name: 'Chris Jones'}, {name: 'Amanda Cullen'}, {name: 'Jeremy Goodwin'} ];
var removeEmployee = 'Chris Jones';
var index = employees.findIndex(e => e.name === removeEmployee);
employees.splice(index, 1);
console.log(employees);
You loop through the list like this:
1
2
3
4
5
for the first iterration you are at index 0. Then you remove index 0 (John Smith). At this point Jackie Jackson is the new index 0 but the iterration jumps to the next element (index 1), what is Chris Jones.
The new index 0 is never logged out to the console! But he is still in the list!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With