0

I need to delete an employee from an array. I need to remove the full object for that employee (all of the key value pairs) with a function that will loop through the array and check for the key value firstName and delete the object based on the name.

Lets say the name is "Mike".

I want to use the splice command and a for loop. this is what I have currently... but I can't get it to detect and delete the object. I just get the full list returned.

function employeeUpdater() {
   for (let key in obj) {
      if (obj[key] === "Theo") {
         Array.splice();
      }
   }
   return(obj)
}  
2
  • Welcome to SO! Can you show your data structure and actual/expected output? Thanks! Commented Nov 15, 2019 at 22:57
  • 1
    Please provide a sample of the data you are working with. A minimal reproducible example in other words. You can use Stack Snippets to make it easier for others to reproduce. Commented Nov 15, 2019 at 22:57

3 Answers 3

1

Array.filter() seems much more appropriate for your task.

const data = [{ name: 'Mike' }, { name: 'Sam' }, { name: 'Sarah' }];

const filtered = data.filter(p => p.name !== 'Mike');

console.log(filtered);

Sign up to request clarification or add additional context in comments.

Comments

1

In order to do this, you must first loop through your array of employees. I am assuming that it is called employees.

The array splice() method has two parameters (for your purpose). The parameters are index and amountToDelete. For example, doing employees.splic(3, 1); will delete the fourth employee from the list.

Here's how you would do it in your context:

employees.forEach(function(obj, index){
    for (let key in obj){
        if (obj[key] === "Theo") {
            employees.splice(index, 1);
        }
    }
});

Comments

0
  1. Get the keys.
  2. Loop through keys, using them with object to get value.
  3. If found, delete, then break as there's no need to continue.
  4. Profit.

    var keys = Object.keys(employees);
    
    keys.forEach(k => {
      if (employees[k] == "Theo") {
        delete employees[k];
        break;
      }
    });
    

3 Comments

This will mutate the original array and OP was requesting for a one which does not .
I believe you misread the title. "delete an object from an array without affecting the rest of the array" means to delete the object without deleting or affecting the other elements.
So you want to make a copy of the array first?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.