Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.');
}
like image 265
AKL012 Avatar asked Dec 21 '25 03:12

AKL012


2 Answers

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);
like image 182
Faly Avatar answered Dec 22 '25 18:12

Faly


Jackie Jackson still in the list

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!

like image 26
Grim Avatar answered Dec 22 '25 19:12

Grim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!