AKL012 AKL012 - 3 years ago 84
Javascript Question

.splice() is removing 2 objects from array instead of 1

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.');
}




Answer Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download